錯誤:java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate(), Statement.executeLargeUpdate() or Connection.prepareStatement().
背景:今天在做數據庫連接池時報了個錯誤,如下圖1所示:
圖1
代碼如下:
<span style="white-space:pre"> </span>1<span style="white-space:pre"> </span>conn = JdbcUtils_DBCP.getConnection();
2 String sql = "INSERT INTO persons(firstname) VALUES(?)";
3 st = conn.prepareStatement(sql);//這行代碼如果是使用mysql-connector-java-5.1.**的包會報這樣的錯誤
st.setString(1, "Wang");
st.executeUpdate();
rs = st.getGeneratedKeys();
按照錯誤提示:第三行代碼加上Statement.RETURN_GENERATED_KEYS,改成st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);就沒有問題。
因爲開發中遇到了這個問題,在此記錄一下,希望大家遇到同樣問題時能夠快速解決。