Problem with add data to mySql with String.format in Java - java

I have problem when i try to add data to mySql Table with String.format.
MySql table:
CREATE TABLE Product (
Product_id int AUTO_INCREMENT,
Name varchar(255),
Description varchar(255),
Price double(9,2),
Primary Key(Product_id)
);
Method, that adds a record to the table. Problem is with column price. In mysql i defined it: Double(9,2). When I add it like this, everything works fine.
public void insertProduct(Product product) {
this.databaseService.performDML(
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '"+product.getPrice()+"')",
product.getName(),
product.getDescription())
);
}
but when adding looks like this, i have exception: "Data truncated for column 'Price' at row 1"
public void insertProduct(Product product) {
this.databaseService.performDML(
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '%f')",
product.getName(),
product.getDescription(),
product.getPrice())
);
}
Can someone tell me the difference, and how i can add data properly with String.format?

Here's the conclusion, use prepared statements instead of building a string yourself for SQL statements.
But if you are really wondering about the difference between the two strings... the main difference is that the price gets padding zeros after the point for doubles if you use String.format() method.
You could simply print the two strings in console to see the difference.
For example, for the price is 12.345:
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '"+product.getPrice()+"')",
product.getName(),
product.getDescription())
The first string gets "12.345".
String.format("INSERT INTO product (name,description,price) " +
"VALUES ('%s', '%s', '%f')",
product.getName(),
product.getDescription(),
product.getPrice())
The second string gets "12.345000".

Related

Spring Data Cassandra custom insert query failing at '.' in String

I have written a custom save query so that I can add a configurable TTL on each item. Here is my repo:
#Repository
public interface MyCassandraRepository extends
TypedIdCassandraRepository<MyCassandraItem, UUID> {
#Query("insert into " + TABLE_NAME + " (" + CQL_UUID + ", " + CQL_PLAN + ") values (?0, ?1) using ttl ?2")
MyCassandraItem customSaveWithTtl(UUID uuid, String plan, Integer ttl);
}
Here is my table:
CREATE TABLE IF NOT EXISTS my_users.plans (
user_id uuid,
plan text,
PRIMARY KEY (user_id)
) ;
However, when I try to add an entry where the plan String contains a full stop/period (eg. eyJhbGciOiJIUzUxMiJ9.hsdyu7832uwhjjdsjkdsew2389dhj), I get the following error:
org.springframework.cassandra.support.exception.CassandraQuerySyntaxException: line 1:110 mismatched input 'eyJhbGciOiJIUzUxMiJ9' expecting ')' (...plan) values ('c7a8fd65-8ef5-420e-b02e-898fe248bbf3', ''[eyJhbGciOiJIUzUxMiJ9]....); nested exception is com.datastax.driver.core.exceptions.SyntaxError: line 1:110 mismatched input 'eyJhbGciOiJIUzUxMiJ9' expecting ')' (...plan) values ('c7a8fd65-8ef5-420e-b02e-898fe248bbf3', ''[eyJhbGciOiJIUzUxMiJ9]....)
Trying to add it manually using CQLSH, I also get an error with the '.':
SyntaxException: line 1:826 no viable alternative at input '.' (... "plan") VALUES (c7a8fd65-8ef5-420e-b02e-898fe248bbf3, [eyJhbGciOiJIUzUxMiJ9].hsdyu7832uwhjjdsjkdse...)
Can anyone see how I can get it to add the whole String and not just stop at the '.'?
You may try using PreparedStatement
String originalPlan = "eyJhbGciOiJIUzUxMiJ9.hsdyu7832uwhjjdsjkdsew2389dhj";
PreparedStatement preparedStatement = cqlTemplate.getSession().prepare("insert into plans (user_id, plan) values (?, ? )");
Statement insertStatement = preparedStatement.bind(UUIDs.timeBased(), originalPlan );
cqlTemplate.execute(insertStatement);

Proper way to add data to a table in postgreSQL using JDBC?

This is my first post here, if my formatting is not correct/ hard to read, I will change it. Please let me know.
I have been playing with JDBC trying to add basic data to a database, using user input data. The user provides first and last name, email, and a user id is generated using the random function.
The database was created using postgreSQL. I'm trying to add to a table called accounts, which contains the following columns - user_id (integer), first_name (varchar(100)), last_name (varchar(100)), email (varchar(500)).
My program is able to connect to the database successfully, but it's not able to add data to the table.
in the following code, firstName, lastName, and eMail are all strings, while sID is an int.
state = conx.prepareStatement("INSERT INTO accounts VALUES ("+ sID +","+ firstName + "," + lastName + "," + eMail) + ")");
s.executeUpdate();
Normally, I'd hope the data would be added to the table so we can call it a day, but I'm getting an error.
org.postgresql.util.PSQLException: ERROR: column "v" does not exist
Position: 36
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
at Main.main(Main.java:49)
org.postgresql.util.PSQLException: ERROR: column "v" does not exist
Position: 36
Use ? for parameters instead of concatenating their values. Also, you should name the columns in the INSERT statement. For example:
s = conx.prepareStatement(
"INSERT INTO accounts (id, first_name, last_name, email) " +
"VALUES (?, ?, ?, ?)"
);
s.setInt(1, sID);
s.setString(2, firstName);
s.setString(3, lastName);
s.setString(4, email);
int affectedRows = s.executeUpdate();

check if row already exists if does not exist insert row otherwise show message

String sql2="if not exists(select * FROM stock where productCode=?)\n" +
"Begin\n" +
"insert into stock "
+ "(productName,quantity,currentQuantity,price,companyName,categoryName,productCode) "
+ "values(?,?,?,?,?,?,?)\n" +
"End";
PreparedStatement pst2 = con.prepareStatement(sql2);
pst2.setString(1,productCodeTextField.getText());
pst2.setString(2,productNameTextField.getText());
pst2.setString(3,quantityTextField.getText());
pst2.setString(4,quantityTextField.getText());
pst2.setString(5,priceTextField.getText());
pst2.setString(6, (String) companyNameJComboBox.getSelectedItem());
pst2.setString(7, (String) categoryNameJComboBox.getSelectedItem());
pst2.setString(8,productCodeTextField.getText());
int x=pst2.executeUpdate();
if(x!=0){
productCodeTextField.setText("");
productNameTextField.setText("");
quantityTextField.setText("");
priceTextField.setText("");
JOptionPane.showMessageDialog(null,"Product entered");
}else{
JOptionPane.showMessageDialog(null,"Product already exists");
}
I am successfully able to check for for already existing products before insertion but i am not able to populate the correct message on the basis of the query executed. The executeUpdate is always returning some value even when the insertion is not being done. How to fix this.
There is an easier solution that may work for you:
Throw away the first query that checks whether the entry already exists
Rewrite sql2 as follows:
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
VALUES (?,?,?,?,?,?)
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
Add: pst.setString(7, productCodeTextField.getText());
executeUpdate() returns an int indicating the number of rows affected by the query. Use this variable to determine if a row was added. If the variable != 0 display success message.
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
select ?,?,?,?,?,?
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
This is how it works for SQL Server. 3 and 4 points same as Coop answered

Database value insertion Error

How can i manually insert values if not exist...i tried following code but it produce error.How can i insert values if not exist in the table
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" memo VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
stmt.executeUpdate(insert);
it produce an error like
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'mem' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
should be
String insert="INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
MySQL (and any other SQL implementation as well) doesn't support IF NOT EXISTS in INSERT queries.
your INSERT query must be
"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
What you want may be INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE....
The former will update an existing row if a duplicate insert is detected, while the latter will just throw away duplicate inserts.
In both cases, you'll have to create a UNIQUE constraint on the column you want to check for duplicates. If the UNIQUE is violated, the alternate function is invoked.

keep column name variable in Java INSERT INTO command with PreparedStatement?

I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.

Categories

Resources