三种获得自动生成主键的方法
来源:互联网 发布:linux开机运行脚本 编辑:程序博客网 时间:2024/04/30 03:55
三种获得自动生成主键的方法,getGeneratedKeys,专用SQL和可更新的结果集
- package test;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
-
-
-
-
-
- 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));
- }
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
- 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;
- }
- }