三种获得自动生成主键的方法

来源:互联网 发布:linux开机运行脚本 编辑:程序博客网 时间:2024/04/30 03:55

三种获得自动生成主键的方法,getGeneratedKeys,专用SQL和可更新的结果集

  1. package test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.ResultSet;  
  6. import java.sql.Statement;  
  7.   
  8. /**
  9. * 三种获得自动生成主键的方法。
  10. *
  11. * @author 赵学庆
  12. *
  13. */  
  14. public class TestGetPK {  
  15.   
  16.   public static void main(String[] args) throws Exception {  
  17.      Class.forName("com.gbase.jdbc.Driver");  
  18.      String url = "jdbc:gbase://localhost/mytest";  
  19.      Connection con = DriverManager.getConnection(url, "root", "111111");  
  20.   
  21.      System.out.println(getPK1(con));  
  22.      System.out.println(getPK2(con));  
  23.      System.out.println(getPK3(con));  
  24.    }  
  25.   
  26.   /**
  27.     * 使用JDBC 3.0提供的 getGeneratedKeys。推荐使用
  28.     *
  29.     * @param con
  30.     * @return
  31.     * @throws Exception
  32.     */  
  33.   public static long getPK1(Connection con) throws Exception {  
  34.      Statement stmt = con.createStatement();  
  35.      stmt.executeUpdate("INSERT INTO t_type (name) values ('Can I Get the Auto Increment Field?')",  
  36.          Statement.RETURN_GENERATED_KEYS);  
  37.   
  38.     int autoIncKeyFromApi = -1;  
  39.      ResultSet rs = stmt.getGeneratedKeys();  
  40.     if (rs.next()) {  
  41.        autoIncKeyFromApi = rs.getInt(1);  
  42.      }  
  43.     return autoIncKeyFromApi;  
  44.    }  
  45.   
  46.   /**
  47.     * 使用数据库自己的特殊SQL.
  48.     *
  49.     * @param con
  50.     * @return
  51.     * @throws Exception
  52.     */  
  53.   public static long getPK2(Connection con) throws Exception {  
  54.      Statement stmt = con.createStatement();  
  55.      stmt.executeUpdate("INSERT INTO t_type (name) values ('Can I Get the Auto Increment Field?')",  
  56.          Statement.RETURN_GENERATED_KEYS);  
  57.   
  58.     int autoIncKeyFromFunc = -1;  
  59.      ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");  
  60.     if (rs.next()) {  
  61.        autoIncKeyFromFunc = rs.getInt(1);  
  62.      }  
  63.     return autoIncKeyFromFunc;  
  64.    }  
  65.   
  66.   /**
  67.     * 使用可更新的结果集。
  68.     *
  69.     * @param con
  70.     * @return
  71.     * @throws Exception
  72.     */  
  73.   public static long getPK3(Connection con) throws Exception {  
  74.      Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,  
  75.         java.sql.ResultSet.CONCUR_UPDATABLE);  
  76.      ResultSet rs = stmt.executeQuery("SELECT * FROM t_Type");  
  77.      rs.moveToInsertRow();  
  78.      rs.updateString("name", "AUTO INCREMENT here?");  
  79.      rs.insertRow();  
  80.      rs.last();  
  81.     int autoIncKeyFromRS = rs.getInt("id");  
  82.     return autoIncKeyFromRS;  
  83.    }  
  84. }
原创粉丝点击