返回首页

gbase数据、南大通用产品文档:GBase8a获取AUTO_INCREMENT 列值方法

更新日期: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();


}

}
}

在.NET 应用程序中使用DSN .........................
39

建议where 条件中的列尽量不使用函数运算,因为加函数运算会造成智能索引失
效,sql 性能降低。

例如:
原始sql 为:
where substr(product_no, 2, 1) in ('3', '4', '5', '8')
智能索引失效,性能非常低。
改写为:
where (product_no like '13%' or product_no like '14%' or product_no like '15%' or
product_no like '18%')'
智能索引将对字符串类型数据前8 个字符的索引。