简体   繁体   中英

preparedstatement not executing properly

This is my code,

String insertSQL = "INSERT INTO customer (c_id, f_name, l_name, address, email, phone)"
                    + " VALUES (?,?,?,?,?,?)";
            PreparedStatement prepStmt = connection.prepareStatement(insertSQL);
            prepStmt.setString(1, c_id);
            prepStmt.setString(2, f_name);
            prepStmt.setString(3, l_name);
            prepStmt.setString(4, address);
            prepStmt.setString(5, email);
            prepStmt.setString(6, telephone);
            runUpdateQuery(prepStmt);

            insertSQL = "INSERT INTO reservation (c_id, book_date, s_time, e_time, amount) "
                    + "VALUES (?,?,?,?,?)";
            prepStmt = connection.prepareStatement(insertSQL);
            prepStmt.setString(1, c_id);
            prepStmt.setString(2, date);
            prepStmt.setDouble(3, startTime);
            prepStmt.setDouble(4, endTime);
            prepStmt.setString(5, amount);
            out.println(prepStmt);
            runUpdateQuery(prepStmt);

The first statement executes and updates the database, but the second doesnt. I have printed the statement out and ran this directly in psql and the sql code is valid, why wont it work?

An error or log message would help both you and us.

Is there no indication of what's wrong besides the absence of the reservation record?

Schema details might help. Perhaps you're violating a primary or foreign key constraint.

I'd refactor those into two separate methods and test them individually.

Are these two INSERTs part of a single transaction? They should be. What do you want to happen if the reservation INSERT fails? Should the user roll back?

Your snippet doesn't show how you clean up your resources. You'd better think about those too, or you'll come to grief later on.

I saw from your own comments that you figured out that the problem was related to JDBC type conversion of dates - glad you resolved it. This sort of issue comes up quite a bit and it's worth getting well-acquainted with JDBC type conversion. The following link is a good explanation and reference:

http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/mapping.html

Over the years, I have referred to the tables at the end of the page repeatedly, and so will you. (I can't find this in the Java 1.7 version of the docs but it should be the same.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM