您的位置:首页 > 其它

返回刚插入的数据的主键

2015-10-02 10:36 357 查看
有时候会需要获取刚刚插入的记录的主键:

使用PrepareStatament的一种重构可以实现返回主键。

PrepareStatament 有多种重构,各自有不同的作用。

package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OtherApi {

public static void main(String[] args) throws SQLException {
int id=create();
System.out.println(id);
}

//获取最近一次插入的数据的主键
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
conn = JdbcUtils.getConnection();
String sql = "insert into user(name,birthday,money)values('name1','1987-1-1',400)";
//prepareStatement的多种重构
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
//使用getGeneratedKeys取得主键的结果集;
rs=ps.getGeneratedKeys();
int id=0;
if(rs.next())
id=rs.getInt(1);
return id;

} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: