I have a problem with a value from my Sql ResultSet
in Java. This value has a single quote (') and that is not valid value. The correct value will be a comma (,). I want to change this single quote(') for a comma (,).
Example of erroneous value: 7'8
Example of the expected result: 7,8
Example of my query and my ResulSet:
String query = "SELECT width,height FROM SizeTable;";
rs = st.executeQuery(query);
while(rs.next()){
String width = rs.getString(1);
String height = rs.getString(2); <--- Here is on I get the error
}
String insert = "INSERT INTO SizeTable2 (Value1,Value2) VALUES('"+width+"','"+height+"')";
st.executeUpdate(insert);
After running I get a SQL message that indicates me an invalid syntax error in my SQL statement ( I want to "Insert Into" width and height value). I can't change this character with MySQL, only with Java.
You can use String::replace
when you get your input :
String height = rs.getString(2).replace("'", ",");
You have to declare your variables outside the loop so you can use them later :
String width = "";
String height = "";
while(rs.next()){
width = rs.getString(1);
height = rs.getString(2).replace("'", ",");
}
Now your sql is open to SQL Injection or Syntax error, to avoid this i suggest to use PreparedStatement instead :
String insert = "INSERT INTO SizeTable2 (Value1,Value2) VALUES(?, ?)";
try (PreparedStatement insert = connection.prepareStatement(insert)) {
insert.setString(1, width);
insert.setString(2, height);
insert.executeUpdate();
}
Note you can insert an empty values so i suggest to check the values before the insert :
if(!width.isEmpty() && !height.isEmpty()){
//prepared statement
}
second thing , i assume that we use real number for width and height so why you are using strings instead, i suggest to change your data type so you can avoid all this problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.