JDBC獲得資料庫產生的主鍵(JDBC、Primary Key)

來源:互聯網
上載者:User
文章目錄
  • 獲得主鍵的代碼  GeneratedKey.java

    JDBC獲得資料庫產生的主鍵 佟強
http://blog.csdn.net/microtong

 

    在實際開發中,資料庫中表的主鍵經常會由資料庫負責產生,INSERT語句插入資料時插入除了主鍵以外的欄位。很多情況下,當INSERT語句提交給資料庫引擎執行完成後,程式需要獲得產生的主鍵以便根據主鍵查詢插入的記錄。JDBC通過在調用語句對象的executeUpdate()方法時,給出第二個參數Statement.RETURN_GENERATED_KEYS
來說明希望資料庫引擎返回產生的主鍵。產生的主鍵以結果集的形式返回,程式調用語句對象的getGeneratedKeys()
方法得到一個結果集。遍曆這個結果集,即得到資料庫產生的主鍵。
    我們以MySQL5.0資料庫為例,建立會員表“member”,其中欄位ID是資料負責產生的自動增量的整數。下列SQL語句建立會員表:
/* 建立MySQL5.0 表member*/
  create table member(
    id int not null auto_increment
,  /*資料庫自動產生的主鍵*/
    name varchar(100),           /*會員姓名*/
    email varchar(255),           /*電子郵件*/
    primary key (id)
  )type = InnoDB default character set gbk;

獲得主鍵的代碼  GeneratedKey.java

package cn.oakcms;
import java.sql.*;
public class GeneratedKey {
    public static void main(String[] args) {
        Connection conn = null;  //連線物件
        Statement stmt = null;   //語句對象
        ResultSet rs = null;      //結果集
        try{
            //載入MySQL驅動程式
            Class.forName("com.mysql.jdbc.Driver");
            //連接字串
            String url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=gbk";
            //建立資料庫連接
            conn = DriverManager.getConnection(url,"root","");
            //建立語句對象
            stmt = conn.createStatement();
            //INSERT語句
            String sql = "insert into member(name,email) values('張三','zhangsan@gmail.com')
";
            //執行INSERT語句,說明要返回資料庫產生的主鍵
            int count = stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

            System.out.println("成功插入"+count+"條記錄!");
            //產生的主鍵以結果集的形式返回
            rs = stmt.getGeneratedKeys();

            //遍曆結果集,輸出主鍵,實際上結果集只有一條記錄
            while(rs.next()){
                long id = rs.getLong(1);
                System.out.println("產生的主鍵是:"+id);
            }
            //關閉結果集、語句、串連
            rs.close(); stmt.close(); conn.close();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(rs!=null) try{rs.close();}catch(Exception ignore){}
            if(stmt!=null) try{stmt.close();}catch(Exception ignore){}
            if(conn!=null) try{conn.close();}catch(Exception ignore){}
        }
    }
}
程式的運行結果如下,每次運行都將插入一條新的記錄,產生一個新的ID。
        成功插入1條記錄!
        產生的主鍵是:6


OakCMS內容管理系統
http://www.oakcms.cn

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.