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));  
    }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM