jdbc java数据库连接 7)获取插入数据的自增长值
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:35
jdbc java数据库连接 7)获取插入数据的自增长值
<div>
卡拉瓦
2024-08-04 10:17:30
</div>
<pre>/**<br/>
*
这是插入一条数据的同时,获取该数据的则增长列的值(该例子的自增长列是id)
*@author LZL
*
*/
public class Auto_Increment { private static Connection conn = null;
private static PreparedStatement stsm = null;
private static ResultSet rs = null; @Test
public void testGetAutoIncrement() {try {<br/> // 1:创建连接<br/> conn = Jdbcutil.getConnection();// 2:设置sql预编译语句
String sql = "INSERT INTO person (NAME,sex,age) VALUES (?,?,?);";// 3:执行sql预编译语句(同时在参数中指定自增列)
stsm = conn.prepareStatement(sql,<br/> PreparedStatement.RETURN_GENERATED_KEYS);// 4:设置参数值
stsm.setString(1, "王五");<br/> stsm.setString(2, "男");<br/> stsm.setInt(3, 22);// 5:发送参数,执行sql
stsm.executeUpdate();// 6:执行完上面的更新数据操作后,获取自增长列
rs = stsm.getGeneratedKeys();<br/> // 7:输出该数据对应的自增长列的值<br/> if (rs.next()) {<br/> System.out.println("刚才添加的数据的自增长列值是:" + rs.getInt(1));<br/> }<br/> } catch (Exception e) {<br/> e.printStackTrace();<br/> throw new RuntimeException(e);<br/> } finally {<br/> }Jdbcutil.close(conn, stsm, rs); } }
<div>






