如何用java中 取到作为数据库主键的值,这个主键是通过序列的个变量

2024-12-19 14:13:14
推荐回答(2个)
回答1:

Oracle的啊 给你个例子,你自己改下表还有insert语句

public int save(User user) throws SQLException {// 插入数据
int id = 0;// 返回用户ID
String sql = "insert into regist_1 values(regist_1seq.nextval,?,?,?,?,?,?)";
String sql2 = "select regist_1seq.currval from dual";
//sql2就是获取序列自增的值,你把regist_1seq换成你自己的

Connection con = ConnectionUtils.openConnection();
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getName());
stmt.setString(3, user.getPassword());
stmt.setInt(4, user.getAge());
stmt.setString(5, user.getSex());
stmt.setString(6, user.getTel());
stmt.executeUpdate();
stmt = con.prepareStatement(sql2);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
id = rs.getInt(1);
System.out.println("save id:" + id + "...");
}
ConnectionUtils.closeResult(rs);
ConnectionUtils.closeStatement(stmt);
ConnectionUtils.closeConnection(con);
return id;
}
不懂可以追问.

回答2:

oracle中有sequence ,可以在数据库中执行create sequence seq_systemid start with 1 increment by 1; 这样在程序中你就可以实现自增长了,如在程序中执行sqi语句:insert into bm values(seq_systemid.nextval,...........);