尝试格式化问题。我有下面提到的一组查询。现在我想要一些功能可以确保所有查询都应该执行或者不执行(如果发生某种错误)我只想维护我的数据库处于适当的状态。
con.setAutoCommit(false);
String qry = "insert into tblAllotment(Employee_ID,Employee_Name,Area,Building_Name,Flat_Type,Flat_No,Date_Application,Date_Allotment,Admin_Code) values(" + id + ",'" + name[1] + "','" + area + "','" + flat[2] + "','" + flat[1] + "','" + flat[0] + "','" + dte + "','" + date + "'," + uid + ")";
String qry1 = "insert into tblFlat_Report(Flat_No,Area_Code,Employee_ID,Date_Allottment,Admin_Code)values('" + flat[0] + "'," + acode + "," + id + ",'" + date + "'," + uid + ")";
//String qry2="UPDATE tblUser_Report t1 JOIN (SELECT MAX(S_Date) s_date FROM tblUser_Report WHERE Employee_ID = "+id+") t2 ON t1.s_date = t2.s_date SET t1.Status = 'A', t1.S_Date ='"+date+"' WHERE t1.Employee_ID ="+id+"";
String qry2 = "insert into tblUser_Report(Employee_ID,Employee_Name,S_Date,Area,Status) values(" + id + ",'" + name[1] + "','" + date + "','" + area + "','A')";
String qry3 = "update tblFlat set Status ='A' where Flat_No='" + flat[0] + "' AND Area_Code=" + acode + " ";
String qry4 = "update tblUser set WL_Flag='N' where Employee_ID=" + id + "";
st = con.createStatement();
int i = st.executeUpdate(qry);
int j = st.executeUpdate(qry1);
int k = st.executeUpdate(qry2);
int l = st.executeUpdate(qry3);
int m = st.executeUpdate(qry4);
con.commit();
if (i != 0 & j != 0 & k != 0 & l != 0 & m != 0) {
Done = "Data Inserted Successfully...!!!";
} else {
System.out.println("Error Occured");
}
} catch (SQLException e) {
con.rollback();
System.out.println(e.getMessage());
}
}
答案 0 :(得分:4)
您的数据库必须提供交易。如果您使用MySQL,则不能使用MyISAM 数据库表,您必须使用InnoDB(例如)。
您在代码开头处开始交易,然后检查每个结果。如果出现错误,则发出回滚。如果一切正常,您最后会发出提交。
你的样子应该是这样的:
con.setAutoCommit(false); // at the beginning, to prevent auto committing at each insert/update/delete
// ... your updates, with error checking
con.commit(); // at the end, only if everything went fine.
如果出现错误,请调用con.rollback()
答案 1 :(得分:2)
在try catch中包装您的查询。在try和commit()的开头添加setAutoCommit(false),在catch块中添加rollback()。
try {
conn.setAutoCommit(false);
// Execute queries
conn.commit();
}
catch (SQLException e) {
conn.rollback();
}