我在我的 Java 应用程序(非 Spring)中使用了 H2 内存数据库。除了我使用 WHERE 过滤器的查询外,我大部分时间都在工作。
以下是我的一些有效方法。
创建表方法(按预期工作):
private void createIntervalETATable() throws SQLException {
Connection connection = DriverManager.getConnection(DB_URL , USER , PASS);
Statement statement = connection.createStatement();
String createTableSQL = "CREATE TABLE tripScheduleETA (" +
"id INT NOT NULL AUTO_INCREMENT," +
"trip_number VARCHAR(255)," +
"booking_id VARCHAR(255)," +
"planned_arrival TIMESTAMP," +
"next_eta_schedule TIMESTAMP," +
"next_destination_geo_code VARCHAR(255)," +
"PRIMARY KEY (id)" +
");";
statement.execute(createTableSQL);
statement.close();
connection.close();
System.out.println("Table `tripScheduleEta` Created");
}
打印所有数据(按预期工作):
public void printAllData() throws SQLException {
Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
Statement statement = connection.createStatement();
String getAllSQL = "SELECT * FROM tripScheduleETA";
ResultSet result = statement.executeQuery(getAllSQL);
while (result.next()) {
int id = result.getInt("id");
String trip_number = result.getString("trip_number");
String booking_id = result.getString("trip_number");
String planned_arrival = result.getString("planned_arrival");
String next_eta_schedule = result.getString("next_eta_schedule");
String next_destination_geocode = result.getString("next_destination_geo_code");
System.out.println(trip_number + " | " + booking_id + " | " + planned_arrival + " | " + next_eta_schedule + " | " + next_destination_geocode);
}
}
按日期范围获取查询(工作):
public JSONArray fetchForETAByDateRange(String dateFrom , String dateTo) throws SQLException {
Connection connection = DriverManager.getConnection(DB_URL , USER , PASS);
Statement statement = connection.createStatement();
String fetchByDateRangeSQL = "SELECT * FROM tripScheduleETA " +
"WHERE next_eta_schedule " +
"BETWEEN '" + dateFrom + "' AND '" + dateTo + "';";
ResultSet result = statement.executeQuery(fetchByDateRangeSQL);
return convertResultSetToJSONArray(result);
}
这是我在 VARCHAR 列上使用 WHERE 子句时遇到问题的地方,它总是返回空,我确定该行存在(尝试过 SELECT *)
public JSONArray fetchByBookingId(String booking_id) throws SQLException{
Connection connection = DriverManager.getConnection(DB_URL , USER , PASS);
Statement statement = connection.createStatement();
String fetchByBookingIdSQL = "SELECT * FROM tripScheduleETA " +
"WHERE booking_id " +
"IN ('" + booking_id + "') ;";
ResultSet result = statement.executeQuery(fetchByBookingIdSQL);
return convertResultSetToJSONArray(result);
}
我尝试在列 ID 上使用 WHERE 子句,我能够得到我需要的行,但是当我使用 VARCHAR 时,我似乎无法得到它。
您应该使用 preparedStatement 并创建一个数组。
PreparedStatement statement =
connection.prepareStatement("Select * from demoTable where test IN (?)");
Array array =
statement.getConnection().createArrayOf("VARCHAR", new Object[]{"a1", "b2","c3"});
statement.setArray(1, array);
ResultSet rs = statement.executeQuery();
发现我过滤查询请求的方式没有问题
IN
和=
都有效,问题是打字错误