我正试图在问题表中插入问题,而不是获得最新的问题id
。我正在尝试在另一个名为select_op
的表中添加它的选项。它成功地插入了问题,但没有插入选项。即使我没有得到任何异常,方法也成功退出。
int id=addQuestions(ques, survey_id);
if(id>0){
//not inserting anyvalue in database
String sql = "insert into select_op("+ "first,"+ "second,"+ "third,"+ "four,"+ "question_id)"+" values(?,?,?,?,?)";
try {
conn.setAutoCommit(false);
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1,option1);
pst.setString(2,option2);
pst.setString(3,option3);
pst.setString(4,option4);
pst.setInt(5,id);
pst.addBatch();
System.out.println(pst.executeBatch());
}catch (BatchUpdateException e) {
try {
System.out.println(e);
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//this function insert data successfully
public int addQuestions(String ques,String survey_id){
String sql = "insert into question(question,survey_id) values(?,?)";
int id = 0;
try {
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1,ques);
pstmt.setString(2,survey_id);
pstmt.addBatch();
pstmt.executeBatch();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
id = keys.getInt(1);
keys.close();
conn.commit();
pstmt.close();
}
catch (BatchUpdateException e) {
try {
conn.rollback();
} catch (Exception e2) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return id;
}
有什么建议吗?
如Zaki所建议你错过了一个承诺吗?
我确实承诺了。。已解决:)感谢
getGeneratedKeys()
在mysql中可能不受支持(我从未见过它被使用或尝试过)。
但我知道这是有效的:执行查询select mysql_insert_id()
会返回最后一个自动增量值——使用它而不是getGeneratedKeys()
。