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?
pricefield takes a numerical value and I always thought that table fields declared as numerical data types shouldn't be enclosed in apostrophes ( ' ... ' ). Try it like this:String.format("INSERT INTO product (name,description,price) VALUES ('%s', '%s', %.3f);", product.getName(), product.getDescription(), product.getPrice()));. On the same token, I've never seen anyone use the String#format() method to build an SQL statement before. I personally have always used Prepared Statements (in Java). It takes care of the apostrophe game.