我是Java JDBC新手,並開發小型數據庫應用程序。我從
O'Reilly - 數據庫編程與JDBC和Java第二版。JDBC:`con.rollback()`只有在`con.commit`沒有成功時纔有效果?
是con.rollback()
只有在con.commit
沒有成功時才起作用?
其實我認爲即使con.commit()
成功,調用con.rollback()
也會起作用。這意味着利用它作爲'撤消'行動。
con.commit()
成功後,我嘗試撥打con.rollback()
,但沒有按我的猜測工作。那麼它是好的還是預期的?
這個例子是從我上面提到的書:
con.rollback()
被註釋。它接近con.close()
之前的結尾。嘗試取消註釋。在con.commit()
成功後con.rollback()
不會回滾事物。
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UpdateLogic
{
public static void main(String args[])
{
Connection con = null;
try
{
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
String url = "jdbc:mysql://localhost:3306/Company";
Statement s;
con = DriverManager.getConnection(url, "root", "");
con.setAutoCommit(false); // make sure auto commit is off!
s = con.createStatement();// create the first statement
s.executeUpdate("INSERT INTO employee VALUES ('1', 'employee 1', '22','00-1234')");
s.close(); // close the first statement
s = con.createStatement(); // create the second statement
s.executeUpdate("INSERT INTO employee VALUES ('2', 'employee 2', '21','00_4321')");
con.commit(); // commit the two statements
System.out.println("Insert succeeded.");
s.close(); // close the second statement
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex)
{
Logger.getLogger(UpdateLogic.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException e)
{
if (con != null)
{
try
{
con.rollback();
} // rollback on error
catch (SQLException i)
{
}
}
e.printStackTrace();
} finally
{
if (con != null)
{
try
{
//con.rollback();
con.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}
它很難弄清楚你在問什麼。如果提交成功,那麼它完成,完成,你不能在這一點回滾。在調用'commit'方法之前,您必須標記事務以回滾***。 – Perception 2013-02-22 19:40:33