Java mysql, Simple update with PreparedStatement has syntax error

This code has some simple syntax error. I fought with him for hours, and I give up. Can you spot it? I bet it's easy. Thanks!

When I update only John's first name, no problem. When I try to update the commented line for the last name, a syntax error.

import java.sql.*; public class UpdateTester { public static void main(String[] args) { try { Connect connect = new Connect(); Connection connection = connect.getConnection(); try { String sql = "UPDATE student SET firstName = ? " + " WHERE studentID = 456987"; //String sql = "UPDATE student SET firstName = ? " // + " Set lastName = ?, " // + " WHERE studentID = 456987"; PreparedStatement pst = connection.prepareStatement(sql); pst.setString(1, "John"); //pst.setString(2, "Johnson"); pst.executeUpdate(); System.out.println("Updated Successfully!"); connection.close(); } catch (SQLException e) { System.out.println("Exception 1!"); e.printStackTrace(); } } catch (Exception e) { System.out.println("Exception 2!"); e.printStackTrace(); } } } 

The column names are correct. Updating the very latest on it also works correctly. Update error with syntax error when trying to perform both actions, as in numbered lines.

+4
source share
1 answer

3 questions:

  • The SET keyword can only be displayed once in an UPDATE statement:
  • Comma before the absence of the second parameter
  • Optional comma before the where clause

Corrected syntax:

 String sql = "UPDATE student SET firstName = ?, " + " lastName = ? " + " WHERE studentID = 456987"; 

SQL Reference

+10
source

All Articles