2016-11-29 39 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(); 
}