java sql empty fields
Hi i am trying to execute query
Statement stmt = conn.createStatement();
stmt.executeUpdate(location_query);
location_query is
insert into table(col, col2) value("2", "");
Both col and col2 are double(12,2) type, i get error
Data truncated for column 'col2' at row 1
, but if I print my query and copy, and paste it to PMA (PhpMyAdmin) its correct.
I guesst that its becouse value of col2 is empty, but is there chance to solve this in other way not to checking all variables which im trying to put to my q开发者_如何学JAVAuery ??
Well, an empty String is not a valid number, therefore different database systems might handle that differently. When you just want that column NULL or filled with the default, you should leave it out like this:
insert into table(col) value(2);
OR set it NULL explicitly:
insert into table(col, col2) value(2, NULL);
Besides, numbers are written without quotes in SQL. Furthermore, you should cosider using PreparedStatements only. PreparedStatements give you type saftly and protect from SQL injection and might be faster when reused.
Take a look at google "statement vs. preparedstatement"
EDIT
Your example would look something like this, when using prepared statements:
String yourFirstString = "2.34";
String yourSecondString = "";
double yourFirstDouble = 0;
double yourSecondDouble = 0;
if(yourFirstString != null && yourFirstString.trim().length() > 0){
try {
yourFirstDouble = Double.parseDouble(yourFirstString);
}catch(NumberFormatException e){
// handle Exception here
}
}
// same parsing for the second double
PreparedStatement stmt = conn.prepareStatement("insert into table (col, col2) value(?, ?)");
stmt.setDouble(1, yourFirstDouble);
stmt.setDouble(2, yourSecondDouble);
stmt.executeUpdate();
精彩评论