Search code examples
javamysqljdbc

MySQLSyntaxErrorException when trying to execute PreparedStatement


I tried to insert a userId (int) and a userName(String) using the PreparedStatement using JDBC using the following method:

public boolean saveUser(int userId, String userName){
    boolean saveStatus = false;
    try {
        connection.setAutoCommit(true);
        String sql = "insert into testtable values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, userId);
        statement.setString(2, userName);
        saveStatus  = statement.execute(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    }finally{
        Connector.closeConnections();
    }
    return saveStatus;
}

I get the following stacktrace:

com.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 '?,?)' at line 1

What am I doing wrong?


Solution

  • PreparedStatement is precompiled statement. you don't have to supply the sql string while executing.

    This should work:

        try {
            connection.setAutoCommit(true);
            String sql = "insert into testtable values(?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            statement.setString(2, userName);
            saveStatus  = statement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return saveStatus;
    }