0
在我的應用程序中,我正在將數據寫入數據庫。 這是數據庫編寫的代碼。Java + Sql數據庫數據回滾不起作用
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseRollback {
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " + "Include in your library path!");
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("PostgreSQL JDBC Driver Registered!");
try {
dbConnection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/MyDB","root","123");
if (dbConnection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return dbConnection;
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
System.out.println(e.getMessage());
e.printStackTrace();
}
return dbConnection;
}
public static void main(String args[]) throws SQLException {
Connection dbConnection = null;
PreparedStatement pstmt = null;
String query = "insert into orders(orderid, execid, exectype, lastprice, lastqty, ordstatus) values(?, ?, ?, ?, ?, ?)";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
pstmt = dbConnection.prepareStatement(query); // create a statement
pstmt.setString(1, "OrderID");
pstmt.setString(2, "Test02");
pstmt.setString(3, "exectype");
pstmt.setDouble(4, 100.00);
pstmt.setInt(5, 100);
pstmt.setString(6,"ordstatus");
pstmt.executeUpdate();
dbConnection.commit();
query.concat("error");
dbConnection.prepareStatement(query);
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
} catch (Exception e) {
// e.printStackTrace();
dbConnection.rollback();
}
finally {
if (pstmt != null) {
pstmt.close();
}
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
}
}
}}
調試點達到the dbConnection.commit();
後我檢查了數據庫,並且插入了一條記錄。但是它接着通過dbConnection.rollback();
部分。但它不會回滾插入的記錄。我如何實現回滾機制?
我已經完成了。結果是一樣的。 :( – 2012-08-15 11:02:36
如果我把
dbConnection.commit()
放在事務結束處,那麼如果在try塊中有一些代碼會給出編譯錯誤,是否可以回滾以前提交的數據? – 2012-08-16 04:22:36就我的理解而言,不可能回滾已提交的數據 – 2012-08-16 04:35:16