如题,我是使用触发器和序列自动生成主键。插入一条记录后该如何返回最新插入的主键值呢?
部分代码如下:
- Java code
public void getlist() throws UnsupportedEncodingException { Connection con = Connect.getCon(); ResultSet rs = null; Statement stm = null; members.clear(); String ctymsql=""; try { con.setAutoCommit(false); stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); int rows = sh.getRows(); System.out.println(rows); String email=""; for (int i = 1; i < rows; i++) { sql.getsql(i); email=sh.getCell(sql.getCytmembermap().get("EMAIL"), i).getContents(); ctymsql = sql.getCtymsql(); ctyhList.add(sql.getCtyhsql()); //ctymList.add(sql.getCtymsql()); ctysList.add(sql.getCtyssql()); //System.out.println(m6699sql); stm.executeUpdate(ctymsql, Statement.RETURN_GENERATED_KEYS); //System.out.println("-------------"); int autoIncKeyFromFunc = -1; rs = stm.executeQuery("select member_autoinc.currval as cur from dual"); if (rs.next()) { autoIncKeyFromFunc = rs.getInt("cur"); members.add(autoIncKeyFromFunc); if(!email.equals("")){ //插入数据表member_email stm.execute("insert into tbl_member_email(MEMBER_ID,EMAIL,FLAG) value("+autoIncKeyFromFunc+",'"+email+"',0)"); } } else { // throw an exception from here } rs.close(); rs = null; } con.commit();
------解决方案--------------------
我当然试过,不然也不会再这里跟你说了,你取不到值一定是其他地方有什么问题。类似的项目我做过很多的。
当然我是通过JDBC实现的,最后顺便说一句 seq_sqlsetence.nextval 你需要取一个别名,不然不好取值,例如语句这么写
select seq_sqlsetence.nextval as id from dual这样你就可以通过res.getString("ID");把值取出来了。