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

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