【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);就没有问题。

因为开发中遇到了这个问题,在此记录一下,希望大家遇到同样问题时能够快速解决。


发布了11 篇原创文章 · 获赞 233 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/zhengwangzw/article/details/52470877
今日推荐