我編寫的程序檢查酒店中可用的房間。我使用JCalendar爲用戶輸入日期和JTable來顯示可用的房間。 問題是,當我點擊檢查可用性按鈕時,它拋出一個SQL異常。使用JTable和JCalendar檢查房間可用性拋出SQL異常
以下是代碼片段:
public class Room_Availability extends JFrame {
//Note: Didn't add codes about instantiating panels, setting layouts and all
JLabel arr_date= new JLabel("Arrival Date:");
JLabel dep_date= new JLabel("Departure Date:");
JButton chk_btn= new JButton("Check Availability");
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
JTable CheckAvail= new JTable();
Room_Availability(){
chk_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
CheckAvailActionPerformed(evt);
}
});
}
private void CheckAvailActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/testing?autoReconnect=true&useSSL=false";
String connectionUser = "root";
String connectionPassword = "admin";
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String query= "select * from room as ro" +
"where ro.room_id not in "+
" ("+
"select re.room_no"+
" from testing.booking as re "+
"where (arrival_date >= ? and departure_date < ?)"+
"or (departure_date >= ? and arrival_date < ?)"+
")";
PreparedStatement pStmt = (PreparedStatement) conn.prepareStatement(query);
java.util.Date utilDate = arrival.getDate();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
java.util.Date utilDate1 = departure.getDate();
java.sql.Date sqlDate1 = new java.sql.Date(utilDate1.getTime());
pStmt.setDate(1, sqlDate);
pStmt.setDate(2, sqlDate1);
pStmt.setDate(3, sqlDate);
pStmt.setDate(4, sqlDate1);
rs = pStmt.executeQuery();
CheckAvail.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace();
}
}
}
當我執行查詢(具有相同的日期,因爲我在JCalendar進入)上的MySQL數據庫這是什麼顯示和應顯示在JTable上:
這是我得到的錯誤:
有4個問題n在你的查詢中標記,這意味着它需要4個參數;你只能指定2個參數。 –
我註釋掉了''或(departure_date> =?和arrival_date <?)「+'',但現在我得到'MySQLSyntaxErrorException' – Tia