环境说明
jdk1.8
dm8
创建表
CREATE TABLE "SYSDBA"."PERSON"
(
"ID" INT IDENTITY(1, 1) NOT NULL,
"NAME" VARCHAR(20),
NOT CLUSTER PRIMARY KEY("ID")) STORAGE(ON "MAIN", CLUSTERBTR) ;
方法1 使用匿名块
String sql1 = "DECLARE id int; BEGIN insert into PERSON(name) values(?) return id into id;?:=id;END;";conn.setAutoCommit(false);CallableStatement statement=conn.prepareCall(sql1);statement.setString(1, "test");statement.registerOutParameter(2,java.sql.Types.INTEGER);statement.executeQuery();String id=statement.getString(2);System.out.println(id);
方法2 使用RETURN_GENERATED_KEYS
String sql = "insert into PERSON(name) values (?) ;";PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);preparedStatement.setString(1,"test");preparedStatement.executeUpdate();ResultSet generatedKeys = preparedStatement.getGeneratedKeys();while (generatedKeys.next()){System.out.println(generatedKeys.getLong(1));}