我的表格包含列 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
值是什么。我怎么能这样做?
答案 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();
//....
答案 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();
试试这个。