preparedStatement.getGeneratedKeys()
工作正常时,查询只有一个INSERT语句中的MySQL,但如果你有在查询多个语句不会返回gernerated标识,即: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);
}
我不知道这个答案将有助于解决您的问题,但它可以编写插入单个语句:
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();
有两个备选方案没有一个变量:
-- "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"
由于司机似乎并不处理多个语句没关系。您也可以尝试删除最后一个分号;
。
附:蒂姆Biegeleisen评论的第一个版本不能在MySQL的工作,他的回答提供了另一种变型。