下面的腳本教您如何獲得自動增長的MySQL主鍵,如果您對MySQL主鍵方面感興趣的話,不妨一看,相信對您學習MySQL主鍵方面會有所啟迪。
- import java.sql.*;
- public class GetKey {
- ResultSet rs = null;
- Connection conn = null;
- Statement stmt = null;
- // 加入同一個連接發生其他查詢,Key會被重寫所以不准確
- public void getId() {
- try {
- getConnect gc = new getConnect();
- conn = gc.getconn();
- Statement stmt = conn.createStatement();
- stmt.executeUpdate("insert into tb (name) values ('Key')");
- rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
- int autoIncKeyFromFunc = -1;
- if (rs.next()) {
- autoIncKeyFromFunc = rs.getInt(1);
- System.out.println("autoIncKeyFromFunc: " + autoIncKeyFromFunc);
- }
- } catch (Exception e) {
- System.out.print("有異常發生!");
- }
- }
- // getGeneratedKeys()是每次創建一個Statement 實例,所以是安全的!
- public void getId_() {
- try {
- getConnect gc = new getConnect();
- conn = gc.getconn();
- stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
- java.sql.ResultSet.CONCUR_UPDATABLE);
- stmt.executeUpdate("insert into tb (name) values ('x')");
- int autoIncKeyFromApi = -1;
- rs = stmt.getGeneratedKeys();
- if (rs.next()) {
- autoIncKeyFromApi = rs.getInt(1);
- System.out.println("Key returned from getGeneratedKeys():"
- + autoIncKeyFromApi);
- }
- } catch (Exception e) {
- System.out.print("有異常發生!");
- }
- }
- public static void main(String[] args) {
- GetKey get = new GetKey();
- get.getId();
- get.getId_();
- }
- }
MySQL主鍵的設計原則
MySQL分區的優點
Mysql分區表對函數的限制
定義MySQL事務的例子
創建MySQL存儲過程示例