java jdbc插入数据后返回该条数据的自增ID值
用户注册是向表中插入用户的基本信息并返回该记录的id值 例子 public long regist(Cuser cuser) { Connection con=Cconnection.getconnection();//Cconnection是的到数据库连接的类 PreparedStatement ps=null; ResultSet rs=null; long id = 0;//存放数据库返回的用户注册过后的id try { ps=con.prepareStatement(Csqlutil.REGIST,Statement.RETURN_GENERATED_KEYS);//将Csqlutil.REGIST改为sql语句 ps.setString(1, cuser.getUsername()); ps.setString(2, cuser.getName()); ps.setString(3, cuser.getPwd()); ps.setInt(4, cuser.getAge()); ps.setString(5, cuser.getSex()); ps.setString(6, cuser.getPhone()); ps.executeUpdate(); rs=ps.getGeneratedKeys();//这一句代码就是得到插入的记录的id while(rs.next()){ id=rs.getLong(1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { rs.close(); ps.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return id; }
- 版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《IT技术宅》。
- 本文网址:https://www.ilt.me/dmfx/84.html
- 上篇文章:DbUtils 详细使用教程
- 下篇文章:java获取properties配置文件值
奇草导航
2016-04-12 08:51 宁夏银川市电信
回复
Windows XP
Firefox 45.0
专业的内容,就不假装也读懂了。留个脚印闪人~~

