用JDBC怎么拿到自动递增的数据?(Oracle)
阅读
我表里的ID字段是自动递增字段
我插入数据用sequence.nextval生成这个ID
我现在想每插入一条记录时,就拿到这个ID
我差API有这么两种方法
- Java code
PreparedStatement psmcnn.prepareStatement("insert into bbs values(seq.nextval,?,?)",Statement.RETURN_GENERATED_KEYS ); ...... psm.executeUpdate(); ResultSet rs = psm.getGeneratedKeys();//获取自动递增字段的结果集 rs.next(); int id = rs.getInt(1) //获取seq.nextval的值
不知这个方法可不可以拿到递增字段的值呢,在mysql下我试了,可以.
但我现在我用的是oracle数据库,为什么每次运行到int id = rs.getInt(1)就报错?
rs.getInt(1)返回的是RowId类型,这个类型怎么转换为int类型?
------解决方案--------------------
你需要首先执行 select seq.nextval from dual 返回一个序列值,然后再用这个值来做插入,这样你就可以得到了这个值了啊。
------解决方案--------------------
先select ROWIDTOCHAR(rowid) as id from your_table;
然后用ResultSet.getString("id");
------解决方案--------------------
select seq.currval from dual
返回sequence的当前值。
rs.getInt(1)报错那就rs.getString(1)试试看咯。
------解决方案--------------------
lz你加个方法不就行了
你插入时的id从以下的方法获得你不就取得id了吗
- Java code
public Integer getId() throws Exception{ Connection conn=null; PreparedStatement pstm=null; ResultSet rs=null; try{ conn=JdbcUtil.getConnection(); String sql="select seq.nextval from dual"; pstm=conn.prepareStatement(sql); rs=pstm.executeQuery(); Integer id=null; if(rs.next()){ id=rs.getInt(1); } return id; }finally{ if(rs!=null) try{ rs.close(); } catch(Exception e){} if(pstm!=null) try{ stm.close(); } catch(Exception e){} if(conn!=null) try{ conn.close(); } catch(Exception e){} } }
------解决方案--------------------
不好意思没仔细看你下面已经写了代码了.
那lz可以参考下我的代码就是我以前在oracle数据库用jdbc写的阅读上一篇:初学者,Java中传值还是传引用 下一篇:返回列表