2016-11-29 30 views
2

私は、次のコードJavaのPreparedStatementの構文の問題

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(); 
    } 
} 

を持っており、近くに構文エラーがあります。 。 setStringとexecuteUpdateの行にあります。

この行の

preparedStatement.setString(1, positionName); 

私は、 " "トークンのトークン"。"、@期待

構文エラーに

構文エラーがあります。トークン上

構文エラーが期待される「;」、このトークン

を削除し、私はそれと間違っているものを見ることができません。

答えて

5

tryステートメントの本体全体を、クローズ可能なリソースを初期化するためだけの部分に置きました。あなたは欲しい:

// 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(); 
}