Java + Sql数据库数据回滚不起作用

问题描述:

在我的应用程序中,我正在将数据写入数据库。 这是数据库编写的代码。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();部分。但它不会回滚插入的记录。我如何实现回滚机制?

dbConnection.commit(); 

应放置在您的交易结束时。

pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee"); 
pstmt.executeUpdate(); // here error comes......... 
dbConnection.commit(); 
     } catch (Exception e) { 
+0

我已经完成了。结果是一样的。 :( – 2012-08-15 11:02:36

+0

如果我把dbConnection.commit()放在事务结束处,那么如果在try块中有一些代码会给出编译错误,是否可以回滚以前提交的数据? – 2012-08-16 04:22:36

+0

就我的理解而言,不可能回滚已提交的数据 – 2012-08-16 04:35:16