我有一个表,其中有一列被定义为自动生成键。执行以下代码时,我希望生成一个新密钥,但事实并非如此。插入了一行,但 ResultSet 为ps.getGeneratedKeys()
空。
我正在使用 DB2:SQLLIB_ADCL_V97FP1。
conn = getConnection();
conn.setAutoCommit(false);
String query =
"INSERT INTO MyTable " +
" (messe_nr, land5, variable_nr, bezeichnung_en, bezeichnung_de) " +
"VALUES (?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, fair.getFairId());
ps.setString(2, variable.getCountryCode());
ps.setInt(3, variable.getSort());
ps.setString(4, variable.getLabel_en());
ps.setString(5, variable.getLabel_de());
log.debug(query);
int count = ps.executeUpdate();
if(count == 1) {
ResultSet rs = ps.getGeneratedKeys();
if(rs.next()) {
variable.setId(rs.getBigDecimal(1).intValue());
} else {
log.error("Could not get autogen key after variable insert");
throw new AVMSException(1500);
}
rs.close();
}
log.debug("inserted " + count);
ps.close();
conn.commit();
Run Code Online (Sandbox Code Playgroud)
更新
我刚刚将项目部署到测试服务器,没有出现问题。我的开发系统出了点问题 - 但是什么?我确实在一两天后安装了 Java 更新 - 1.7.0_13 - 这会导致这样的问题吗:-/?
小智 7
您应该传递“Statement.RETURN_GENERATED_KEYS”作为PreparedStatement 的第二个参数。代码如下所示:-
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name?user=databse_username&password=database_password");
PrepardStatement ps = conn.prepareStatement("INSERT INTO author(authorName) values(?)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "Mark Twain");
int i = ps.executeUpdate();
System.out.println(i + " Records Added.");
ResultSet gK = ps.getGeneratedKeys();
if(gK.next()) {
long generatedId = gK.getLong(1);
} else {
System.out.println("Message => Generated Key cannot be accessed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
这里“author”是表名,“authorName”是列名。
试试这个,它对我有用:
prepStmt = con.prepareStatement(sql, new String[]{"YOUR_ID_FIELD"});
//Setting Bind-Variables
prepStmt.executeUpdate();
rs = prepStmt.getGeneratedKeys();
while (rs.next())
{
tAdresse.getAdressid().setValue(rs.getInt(1));
System.out.println("Key: " + tAdresse.getAdressid().getIntValue());
}
Run Code Online (Sandbox Code Playgroud)