更新日期:2024年09月11日
本示例实现了使用Statement.getGeneratedKeys()获取AUTO_INCREMENT
列的值。
示例如下:
package com.gbase.jdbc.simple;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SampleGetGeneratedKeys {
public static void main(String[] args) {
try {
(new SampleGetGeneratedKeys()).test();
} catch (Exception ex) {
}
}
public void test() throws Exception {
Connection conn = null;
try {
Class.forName("com.gbase.jdbc.Driver").newInstance();
conn = DriverManager
.getConnection("jdbc:gbase://192.168.5.210:5258/test?user=root&p
assword=");
GBase 8a 程序员手册JDBC 篇
- 146 -
南大通用数据技术股份有限公司
Statement stmt = null;
ResultSet rs = null;
try {
// 创建Statement 对象
stmt = conn.createStatement(
java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
// 创建表
stmt.executeUpdate("DROP
TABLE
IF
EXISTS
autoIncTutorial");
stmt.executeUpdate("CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+
"dataField
VARCHAR(64),
PRIMARY
KEY
(priKey))");
// 插入一条数据
stmt.executeUpdate("INSERT
INTO
autoIncTutorial
(dataField) "
+ "values ('Can I Get the Auto Increment
Field?')",
Statement.RETURN_GENERATED_KEYS);
// 使用Statement.getGeneratedKeys()获取自增一字段
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
}
rs.close();
rs = null;
System.out.println("Key
returned
from
GBase 8a 程序员手册JDBC 篇
南大通用数据技术股份有限公司
- 147 -
getGeneratedKeys():"
+ autoIncKeyFromApi);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
}
} catch (SQLException ex) {
// 处理错误
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
conn.close();
}
}
}