Java中SQL查询Access时间字段出现数据类型不兼容报错求助
Access数据库UCanAccess查询时间字段报错排查方案
问题背景
开发A-level休闲中心预订系统时,使用Access数据库存储健身房预订数据,GYM表的EntryTime为时间类型,执行SQL查询时触发数据类型不兼容错误:net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::5.0.1 incompatible data types in combination
当前查询代码片段:
}System.out.println(Selected); ArrayList<Booking> currentBookings = BookingSQL.Bookings("SELECT * FROM GYM WHERE BookingDate = '" + Selected + "' AND EntryTime = '13:00'"); for (int i = 0; i < currentBookings.size(); i++) { System.out.println(currentBookings.get(i).toString()); } } }
已尝试直接使用'13:00'字符串、传入java.sql.Time变量,均未解决问题。
解决方案
1. 采用Access时间字面量格式
Access的时间类型字段要求用#包裹时间值,而非单引号。由于Access时间类型默认包含时分秒,需使用完整格式匹配:
ArrayList<Booking> currentBookings = BookingSQL.Bookings("SELECT * FROM GYM WHERE BookingDate = '" + Selected + "' AND EntryTime = #13:00:00#");
2. 使用PreparedStatement绑定参数(推荐)
直接拼接SQL字符串易引发类型不兼容,还存在SQL注入风险。改用PreparedStatement让JDBC自动处理类型转换:
// 修改BookingSQL类的Bookings方法 public static ArrayList<Booking> Bookings(String bookingDate, Time entryTime) throws SQLException { ArrayList<Booking> bookings = new ArrayList<>(); String sql = "SELECT * FROM GYM WHERE BookingDate = ? AND EntryTime = ?"; try (Connection conn = getConnection(); // 替换为你的数据库连接获取方法 PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, bookingDate); pstmt.setTime(2, entryTime); try (ResultSet rs = pstmt.executeQuery()) { while (rs.next()) { // 将ResultSet数据映射到Booking对象 Booking booking = new Booking(); // 示例:booking.setId(rs.getInt("BookingID")); // 补充其他字段映射逻辑 bookings.add(booking); } } } return bookings; }
调用示例:
Time targetTime = Time.valueOf("13:00:00"); ArrayList<Booking> currentBookings = BookingSQL.Bookings(Selected, targetTime);
3. 验证Access表字段类型
确认GYM表的EntryTime字段类型为时间/日期分类下的“时间”格式,而非文本类型。若字段为文本,需调整查询逻辑或修改字段类型为时间类型。
内容的提问来源于stack exchange,提问作者Henry_Jones
相关产品推荐
相关产品推荐

