zoukankan      html  css  js  c++  java
  • Java中向数据库中插入记录并返回该记录的id值

    用户注册是向表中插入用户的基本信息并返回该记录的id值

    public long regist(Cuser cuser) {
      Connection con=Connection.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;
     }

    2. 使用jdbc 3.0 提供的getGeneratedKeys(推荐使用)

    Statement stmt = conn.createStatement();  
    stmt.executeQuery("INSERT INTO table_name(...) values(...)",Statement.RETURN_GENERATED_KEYS);  
    ResultSet rs = stmt.getGeneratedKeys();  
    if(rs.next()){  
        this.setId(rs.getInt(1));  
        }  
  • 相关阅读:
    python3 网络编程
    python3 字典及其方法
    洛谷P2239 螺旋矩阵
    洛谷P4281 紧急会议
    洛谷 P4427 求和
    树的直径
    洛谷P3398 仓鼠找suger
    洛谷P3865 ST表
    洛谷P1638逛画展
    洛谷P1886 滑动窗口
  • 原文地址:https://www.cnblogs.com/meizhoulqp/p/11592019.html
Copyright © 2011-2022 走看看