我是
Java JDBC的新手,并开发了小型数据库应用程序.我正在学习
O’Reilly – 使用JDBC和Java第2版进行数据库编程.
con.rollback()只有在如果没有成功的情况下才有效吗?
实际上我猜即使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();
}
}
}
}
}