我正在尝试在问题表中插入问题而不是获取最新问题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;
}
有任何建议吗?
答案 0 :(得分:1)
正如扎基建议的那样 你错过了提交吗?
我确实犯了..解决了:) 感谢
答案 1 :(得分:0)
getGeneratedKeys()
(我从未见过它或尝试过它)。
但我确实知道这有效:执行查询select mysql_insert_id()
会返回上一个自动增量值 - 使用该值代替getGeneratedKeys()
。