Java + Sql数据库数据回滚无法正常工作

时间:2012-08-15 10:45:09

标签: sql rollback jaas

在我的应用程序中,我正在将数据写入数据库。 这是数据库编写的代码。

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();部分。但它不会回滚插入的记录。如何实现回滚机制?

1 个答案:

答案 0 :(得分:1)

dbConnection.commit();

应放在交易结束时。

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