我是 Java JDBC 新手,开发了一个小型数据库应用程序。我正在学习O'Reilly - Database Programming with JDBC and Java 2nd Edition。
con.rollback()
只有con.commit
不成功 才有效果?
我预计con.rollback()
即使con.commit()
成功,调用也会产生效果。换句话说,将其用作“撤消”操作。
con.rollback()
成功后我尝试调用con.commit()
,但它没有按预期工作。可以/预期吗?
这个例子来自我上面提到的书:
调用con.rollback()
被注释掉。之前已经接近尾声了con.close()
。我尝试取消注释并运行它。但是,成功con.rollback()
后不会回滚con.commit()
。
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();
}
}
}
}
}