1

I'm new to java, i want to update my database table columns. but when running this code I'm getting this error.

execom.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 'Mcgreth' at line 1

I tried for 1 week. but I cant even think where's the wrong. plzz help me.. thanks a lot for help.this is my code.

public boolean update(File2nd dt) {

    try {            
        con = (Connection) DriverManager.getConnection(url, username, password);//get the connection
        String query = "UPDATE file1  SET  name='" + dt.getName()+ "',age='" + dt.getAge()+ "',color="+dt.getColor()+ ""

                + " WHERE name=" + dt.getName();

        pst = (com.mysql.jdbc.PreparedStatement) con.prepareStatement(query);            
        pst.executeUpdate();
        System.out.println("Updated queries: ");
        return true;
       } catch (Exception e) {
        System.out.println("exe" + e);
        return false;
       } finally {
        try {
              if (pst != null) {
                pst.close();
              }
              if (con != null) {
                con.close();
              }
           } catch (Exception e) {
           }
      }
}
0

1 Answer 1

3

You miss the single quotes for the color field, and in the where clause.

"UPDATE file1  SET  name='" + dt.getName()+ "',age='" + dt.getAge()+ "',color='"+dt.getColor()+ "'"
+ " WHERE name='" + dt.getName() + "'";

Also, you should use paramaterized statements, for a lot of reasons: protection against sql injection, improved readability and often more efficient query execution by your DBMS.

"UPDATE file1  SET  name=?,age=?,color=? WHERE NAME =?";

pst.setString(1, dt.getName());
pst.setInt(2, dt.getAge());
(etc...)
Sign up to request clarification or add additional context in comments.

2 Comments

I was just about to add an answer involving PreparedStatement with ? placeholders and you beat me to it! Reasons include ease of maintainability and protection from SQL injection attacks.
thank u soo much NickJ... it worked.. And i would like to know how to keep a selected row in jtable colored. plz help me with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.