javaweb學習總結(三十七)——獲得MySQL數據庫自動生成的主鍵


  測試腳本如下:

1  create table test1
2 (
3      id int primary key auto_increment,
4      name varchar(20)
5 );

  測試代碼:

 1 package me.gacl.demo;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import me.gacl.utils.JdbcUtils;
 7 
 8 public class Test {
 9     public static void main(String[] args) {
10         Connection conn = null;
11         PreparedStatement st = null;
12         ResultSet rs = null;
13         try{
14             conn = JdbcUtils.getConnection();
15             String sql = "insert into test1(name) values(?)";
16             st = conn.prepareStatement(sql);
17             st.setString(1, "aaa");
18             st.executeUpdate();
19             //獲取數據庫自動生成的主鍵
20             rs = st.getGeneratedKeys();
21             if(rs.next()){
22                 System.out.println(rs.getInt(1));
23             }
24         }catch (Exception e) {
25             e.printStackTrace();
26         }finally{
27             JdbcUtils.release(conn, st, rs);
28         }
29     }
30 }

 


免責聲明!

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



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