使用JDBC获取数据库自动生成的主键

 

使用JDBC获取数据库自动生成的主键:

注:此参数仅对insert操作有效

在数据库中生成users表:

create table users(

id int primary key auto_increment,

name varchar(40),

password varchar(40),

email varchar(60),

birthday date

)

向该表中插入一行记录,然后得到自动增长的id的实现:

Connection con = null;

       PreparedStatement st = null;

       ResultSet rs = null;

       try {        

           //获取连接

           con = DBManager.getConnection();

           String sql="insert into users(name,password) value(?,?)";

           st = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

 

           st.setString(1,"Jerry");

           st.setString(2,"QAZ");

          

           st.executeUpdate();

          

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

           if(rs.next()){

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

           }

          

           DBManager.release(con, st, rs);

       } catch (SQLException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

 

MySql数据库的处理连接:

public class DBManager {

   

    private static String username;

    private static String password;

    private static String url;

    private static String driver;

   

    static{

       try{

           InputStream in = DBManager.class.getClassLoader().getResourceAsStream("db.properties");

           Properties prop = new Properties();

           prop.load(in);

          

           driver = prop.getProperty("driverClassName");

           url = prop.getProperty("url");

          

           username = prop.getProperty("username");

           password = prop.getProperty("password");

          

           Class.forName(driver);

          

       }catch (Exception e) {

           throw new ExceptionInInitializerError(e);

       }

    }

   

   

    public static Connection getConnection() throws SQLException{

       return DriverManager.getConnection(url, username, password);

    }

   

   

    public static void release(Connection conn,Statement st,ResultSet rs){

      

       if(rs!=null){

           try{

              rs.close();

           }catch (Exception e) {e.printStackTrace();}

            rs = null;

       }

       if(st!=null){

           try{

              st.close();

           }catch (Exception e) {e.printStackTrace();}

           st = null;

       }

       if(conn!=null){

           try{

              conn.close();

           }catch (Exception e) {e.printStackTrace();}

           conn = null;

       }

      

    }

   

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值