How to avoid MySQLSyntaxErrorException

I use Java to insert some data into mysql. But the presence of an apostrophe (punctuation mark) in the data (near the weekly tracker suggests that the work is growing) gives me a MySQLSyntaxErrorException. Please give me the correct solution to handle this

Code I have isa

void insert(String a1,String a2, String a3) {
  String nt = a2;
  String pt = a3;
  String tb = a1; 
  query = "insert into "+tb+"(head,des) values('"+nt+"','"+pt+"')"; 
  try {
    stmt.executeUpdate(query);
    System.out.println("inserted"); //con.close();
  } catch (SQLException ex) {
    // Logger.getLogger(conec.class.getName()).log(Level.SEVERE, null, ex);
    ex.printStackTrace();
  }
}
+3
source share
2 answers

Use query parameters rather than string concatenation. This will allow the database driver to format the values ​​sent to the database server instead of reinventing the wheel on its own.

String sql = "insert into ... values (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, nt);
stmt.setString(2, pt);
stmt.executeUpdate();
+6
source
query = "insert into "+tb+"(head,des) values('"+nt+"','"+pt+"')";

it should be

query = "insert into "+tb+" (head, des) values ('"+nt+"','"+pt+"')";

Please make these changes and let me know if there are any more problems ....

+1
source

All Articles