preparedStatement.getGeneratedKeys()
可以很好地工作,但是如果查询中有多个语句,它将不会返回gerned的ID,即:test
具有(ID(PK ,auto_increment),名称,贷款)列:
sqlQuery = "SET @Loan = (SELECT Loan FROM customers WHERE CID = 4);"
+ "INSERT INTO test(Name, Loan) VALUES('jihad', @Loan);";
PreparedStatement st = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys();
if (rs.next()) {
int id = rs.getInt(1);
System.out.println("Generated ID: "+ id);
}
答案 0 :(得分:2)
我不知道此答案是否可以帮助您解决问题,但是可以将插入内容写成一条语句:
sqlQuery = "INSERT INTO test (Name, Loan) ";
sqlQuery += "SELECT 'jihad', (SELECT Loan FROM customers WHERE CID = 4)";
PreparedStatement st = connection.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
答案 1 :(得分:1)
有两种不带变量的选择:
-- "INSERT INTO test(Name, Loan) VALUES('jihad', (SELECT Loan FROM customers WHERE CID = 4))"
"INSERT INTO test(Name, Loan) SELECT 'jihad', Loan FROM customers WHERE CID = 4"
由于驱动程序似乎无法处理多个语句,所以可以。您也可以尝试删除最后一个分号;
。
P.S。 正如Tim Biegeleisen所说,第一个版本在MySQL上不起作用,他的回答提供了另一个变体。