如何在插入新记录时从数据库中获取自动生成的值?

时间:2013-11-21 23:30:17

标签: java jdbc

我的表格包含列 ID,名称,地址,城市,州,邮编。这里插入新记录时会自动生成 id insert into table1(name,address,city,state,zip) values(?,?,?,?,?)

这是我的代码:

preparedstatement.setString(1,name);
preparedstatement.setString(2,address);
preparedstatement.setString(3,city);
preparedstatement.setString(4,state);
preparedstatement.setString(5,zip);

preparedstatement.executeUpdate();

现在我想知道自动生成的id值是什么。我怎么能这样做?

2 个答案:

答案 0 :(得分:6)

使用附加标记Statement.RETURN_GENERATED_KEYS创建预准备语句并使用PreparedStatement.getGeneratedKeys()

String sql = "insert into table1(name,address,city,state,zip) values(?,?,?,?,?)";
PreparedStatement preparedstatement
= con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

//....

preparedstatement.setString(1,name);
preparedstatement.setString(2,address);
preparedstatement.setString(3,city);
preparedstatement.setString(4,state);
preparedstatement.setString(5,zip);

preparedstatement.executeUpdate();

ResultSet generatedKeys = preparedstatement.getGeneratedKeys();
//....

相关:PreparedStatement with Statement.RETURN_GENERATED_KEYS

答案 1 :(得分:3)

String query = <your query>;

PreparedStatement preparedstatement= 
       con.prepareStatement(query ,Statement.RETURN_GENERATED_KEYS)

preparedstatement.setString(1,name);
preparedstatement.setString(2,address);
preparedstatement.setString(3,city);
preparedstatement.setString(4,state);
preparedstatement.setString(5,zip);

执行更新后,

ResultSet rs = preparedstatement.getGeneratedKeys();

试试这个。