简单总结了一下我目前知道的方法。
- package test;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- /**
- * 三种获得自动生成主键的方法。
- *
- * @author 赵学庆 www.java2000.net
- *
- */
- public class TestGetPK {
- public static void main(String[] args) throws Exception {
- Class.forName("com.gbase.jdbc.Driver");
- String url = "jdbc:gbase://localhost/mytest";
- Connection con = DriverManager.getConnection(url, "root", "111111");
- System.out.println(getPK1(con));
- System.out.println(getPK2(con));
- System.out.println(getPK3(con));
- }
- /**
- * 使用JDBC 3.0提供的 getGeneratedKeys。推荐使用
- *
- * @param con
- * @return
- * @throws Exception
- */
- public static long getPK1(Connection con) throws Exception {
- Statement stmt = con.createStatement();
- stmt.executeUpdate("INSERT INTO t_type (name) values ('Can I Get the Auto Increment Field?')",
- Statement.RETURN_GENERATED_KEYS);
- int autoIncKeyFromApi = -1;
- ResultSet rs = stmt.getGeneratedKeys();
- if (rs.next()) {
- autoIncKeyFromApi = rs.getInt(1);
- }
- return autoIncKeyFromApi;
- }
- /**
- * 使用数据库自己的特殊SQL.
- *
- * @param con
- * @return
- * @throws Exception
- */
- public static long getPK2(Connection con) throws Exception {
- Statement stmt = con.createStatement();
- stmt.executeUpdate("INSERT INTO t_type (name) values ('Can I Get the Auto Increment Field?')",
- Statement.RETURN_GENERATED_KEYS);
- int autoIncKeyFromFunc = -1;
- ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
- if (rs.next()) {
- autoIncKeyFromFunc = rs.getInt(1);
- }
- return autoIncKeyFromFunc;
- }
- /**
- * 使用可更新的结果集。
- *
- * @param con
- * @return
- * @throws Exception
- */
- public static long getPK3(Connection con) throws Exception {
- Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
- java.sql.ResultSet.CONCUR_UPDATABLE);
- ResultSet rs = stmt.executeQuery("SELECT * FROM t_Type");
- rs.moveToInsertRow();
- rs.updateString("name", "AUTO INCREMENT here?");
- rs.insertRow();
- rs.last();
- int autoIncKeyFromRS = rs.getInt("id");
- return autoIncKeyFromRS;
- }
- }