当前位置:操作系统 > Unix/Linux >>

获得数据库自动生成的主键

 

示例:

 

packagecom.hbsi.test;

 

 

 

importjava.sql.Connection;

 

importjava.sql.PreparedStatement;

 

importjava.sql.ResultSet;

 

importjava.sql.SQLException;

 

importjava.sql.Statement;

 

 

 

importcom.hbsi.utils.DBManager;

 

 

 

public class Demo4{

 

 

 

      /**

 

       *@param args

 

       */

 

      public static void main(String[] args) {

 

           // TODO Auto-generated method stub

 

           Connection con=null;

 

           PreparedStatement st=null;

 

           ResultSet rs=null;

 

         

 

           try {

 

                 con=DBManager.getConnection();

 

                 String sql="insert intousers (name,password) values (?,?)";

 

                 st=con.prepareStatement(sql);

 

               

 

                 st.setString(1,"Jerry");

 

                 st.setString(2,"QAZ");

 

               

 

                 st.executeUpdate();

 

               

 

                 rs=st.getGeneratedKeys();//结果集单行单列

 

                 if(rs.next()){

 

                      System.out.println(rs.getInt(1));

 

                 }

 

               

 

           } catch (SQLException e) {

 

                 // TODO Auto-generated catchblock

 

                 e.printStackTrace();

 

           } finally{

 

                 DBManager.release(con, st, rs);

 

           }

 

         

 

      }

 

 

 

}

 

摘自 张晓丛的专栏

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,