1. 程式人生 > >【JavaEE】SQLException:Generated keys not requested. You need to specify Statement.RETURN_GE

【JavaEE】SQLException:Generated keys not requested. You need to specify Statement.RETURN_GE

錯誤: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);就沒有問題。

因為開發中遇到了這個問題,在此記錄一下,希望大家遇到同樣問題時能夠快速解決。