尝试使用jdbc事务向数据库表输入值

时间:2014-12-06 17:30:00

标签: java mysql jdbc prepared-statement

我尝试使用数据库事务为表保留输入一组值,重新组合。没有抛出异常,但是没有输入值到DB.Here我已经使用了java.sql.PreparedStatement。

public boolean addReservation(Reservation res, ArrayList<ReservationDetails> resdetlist) throws Exception {
    connection = DBConnection.getDBConnection();
    try {
        System.out.println("A");
        connection.setAutoCommit(false);
        PreparedStatement ps1 = connection.prepareStatement("insert into reservation values(?,?,?,?)");
        ps1.setString(1, res.getResid());
        ps1.setBoolean(2, res.isCheckin_status());
        ps1.setString(3, res.getRes_from());
        ps1.setString(4, res.getRes_till());
        int addedres = ps1.executeUpdate();
        System.out.println("addres:" + addedres);
        System.out.println("B");
        if (addedres > 0) {
            for (ReservationDetails resdet : resdetlist) {
                //int addedresdet = addReservationDetails(resdet);
                PreparedStatement ps2 = connection.prepareStatement("insert into resdetails values(?,?,?,?,?,?)");
                ps2.setString(1, resdet.getResid());
                ps2.setString(2, resdet.getNic());
                ps2.setString(3, resdet.getPayment_id());
                ps2.setString(4, resdet.getRoom_no());
                ps2.setString(5, resdet.getType_of_accomodation());
                ps2.setString(6, resdet.getDate_of_reservation());
                int addedresdet = ps2.executeUpdate();
                System.out.println("addedresdet:" + addedresdet);
                System.out.println("C");
                if (addedresdet <= 0) {
                    System.out.println("D");
                    connection.rollback();
                    return false;
                }
            }

        } else {
            System.out.println("E");
            connection.rollback();
            return false;
        }
        connection.commit();
    } catch (Exception ex) {
        // ex.printStackTrace();
        connection.rollback();
    } finally {
        connection.setAutoCommit(true);
        System.out.println("F");
    }
    return true;

}

1 个答案:

答案 0 :(得分:0)

如果executeUpdate()返回<= 0,则数据库中没有任何更改,因此无需回滚事务。此外,如果在插入条目时发生问题(例如,约束违规等),则executeUpdate()会抛出SQLException。我会将您的代码更改为:

try {
   connection.setAutoCommit(false);
   PreparedStatement ps1 = ...
   ...
   ps1.executeUpdate();
   for (ReservationDetails resdet : resdetlist) {
       PreparedStatement ps2 = ...
       ...
       ps2.executeUpdate();
   }
   connection.commit();
} catch (SQLException e) {
   connection.rollback();
}

另外,请不要忘记在使用close()之后调用PreparedStatements,并在方法结束时调用connection对象。