【发布时间】:2017-11-05 11:15:53
【问题描述】:
我已在数据库中将stdImage 设置为不为空,当我不插入图像时,它会引发错误,但 con.commit() 仍然可以正常工作,并且数据而不是 rollback() 可以在没有图像的情况下保存到数据库请有人解决此代码中的逻辑错误。实际上 rollback() 不起作用。我会很感激的。
public void stdSave(String stdID, String stdName, String fName, String sSec, String contactNo, Date bdate, String address, byte[] image) throws RemoteException, SQLException {
String stdQuery = "INSERT INTO dbo.StudentTable (stID, stName, stFName, classSection,"
+ "contact, date, pAddress) VALUES (?, ?, ?, ?, ?, ?, ?)";
String imgQuery = "INSERT INTO dbo.StdImage (stdID, stdImage) VALUES (?, ?)";
Savepoint save = null;
try {
try(PreparedStatement stmt = con.prepareStatement(stdQuery);
PreparedStatement stmt1 = con.prepareStatement(imgQuery)) {
con.setAutoCommit(false);
save = con.setSavepoint();
stmt.setString(1, stdID);
stmt.setString(2, stdName);
stmt.setString(3, fName);
stmt.setString(4, sSec);
stmt.setString(5, contactNo);
stmt.setDate(6, bdate);
stmt.setString(7, address);
stmt.execute();
stmt1.setString(1, stdID);
stmt1.setBytes(2, image);
stmt1.execute();
}
}
catch(Exception e) {
try {
con.rollback(save);
}
catch (Exception e1) {
JOptionPane.showConfirmDialog(null, "Cannot add the student to database " + e);
}
}
con.commit();
}
【问题讨论】: