Pixels Pixels - 11 months ago 70
Java Question

java PreparedStatement syntax issue

I have the following code

public void savePosition(String positionName) {
String sqlStatement = "INSERT INTO positions (name) VALUES (?)";
try (
Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sqlStatement);
preparedStatement.setString(1, positionName);
preparedStatement.executeUpdate();
){

} catch (SQLException e) {
e.printStackTrace();
}
}


And have a syntax error near , ; . in setString and executeUpdate rows.

For this row

preparedStatement.setString(1, positionName);

I have

Syntax error on token ".", @ expected

Syntax error on token ",", . expected

Syntax error on token ";", delete this token

I can't see what is wrong with it.

Answer Source

You've put the entire body of your try statement into the part that's meant to only be for initializing closeable resources. You want:

// This part is initializing resources
try (Connection connection = getConnection();
     PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
    // This part is just statements
    preparedStatement.setString(1, positionName);
    preparedStatement.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}