Dar*_*Jon 10 java postgresql jdbc insert amazon-redshift
在使用AWS Redshift时,我注意到使用以下任一方法无法通过JDBC驱动程序从具有标识列的表中获取最后一个插入的id:
RETURNING key word
Run Code Online (Sandbox Code Playgroud)
要么
Statement.RETURN_GENERATED_KEYS
Run Code Online (Sandbox Code Playgroud)
如Stack Overflow条目中所述:
由于Redshift(截至2013年10月17日)是基于PostgreSQL版本8.0.2构建的,因此无法使用上述方法.请参阅以下链接中的以下文档:
http://docs.aws.amazon.com/redshift/latest/dg/c_high_level_system_architecture.html
如果您打算将Redshift用作RDBMS,那么阅读以下内容也是值得的:
http://docs.aws.amazon.com/redshift/latest/dg/c_redshift-and-postgres-sql.html
题:
通过PostgreSQL JDBC驱动程序在Redshift中的自动增量/串行/标识列上检索最后插入的id的最佳策略是什么?
鉴于 Redshift 引擎是基于 PostgreSQL 8.0.2 构建的,并且上述 RETURNING 和 Statement.RETURN_GENERATED_KEYS 选项不可用,并且 Redshift 不支持 CREATE SEQUENCE 来使用 CURRVAL/NEXTVAL 函数套件,一种选择是将两个 SQL 语句分组JDBC 事务中的 INSERT 和 SELECT MAX([identity column]) 一起使用。
try {
// create the JDBC connection
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
// start the transaction
conn.setAutoCommit(false);
// create the prepared statement for insert
PreparedStatement prpd = conn.prepareStatement(SQL_INSERT_STATEMENT);
// set input/output parameters as needed...
// execute the SQL prepared statement
int j = prpd.executeUpdate();
// create a statement for select max()
Statement stmt = conn.createStatement();
// execute the statement to return a result set
ResultSet key = stmt.executeQuery(SQL_SELECT_MAX_STATEMENT);
// initialize and retrieve the incremented identity value, in this case it is a long (bigint data type in Redshift)
long id = 0;
if (key.next()) {
id = key.getLong(1);
}
// commit the entire transaction
conn.commit();
} catch (SQLException se) {
// if an SQL exception occurs, rollback the whole deal
try {
if (conn!=null && !conn.isClosed()) {
conn.rollback();
}
} catch (Exception e) {
}
} catch (Exception e) {
// roll back if something other than an SQLException occurs
try {
if (conn!=null && !conn.isClosed()) {
conn.rollback();
}
} catch (Exception e) {
}
} finally {
// do whatever you want to return a value, shut down resources
// close out JDBC resources
try {
if (conn!=null && !conn.isClosed()) {
conn.setAutoCommit(true);
}
} catch (SQLException se) {
}
try {
if (prpd!=null && !prpd.isClosed()) {
prpd.close();
}
} catch (SQLException se) {
}
try {
if (stmt!=null && !stmt.isClosed()) {
stmt.close();
}
} catch (SQLException se) {
}
try {
if (conn!=null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException se) {
}
}
Run Code Online (Sandbox Code Playgroud)
如果 SQL_INSERT_STATEMENT 写入/锁定单个表,则上述方法将起作用。多个表锁需要使用synchronized 关键字来防止死锁。选择锁定的表将允许在结果集中返回递增的标识值。
| 归档时间: |
|
| 查看次数: |
3354 次 |
| 最近记录: |