我有一个数据库,我在其中使用tiemstamps保存消息。我用这段代码创建了表:
CREATE TABLE messages (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
msgid VARCHAR(64) UNIQUE,
payload TEXT,
sender VARCHAR(255),
cur_timestamp TIMESTAMP(3)
);
这一切都很完美。但是,现在我尝试删除时间戳早于用户指定的某些行。这是在我的系统的Java部分完成的,如下所示:
// get current timestamp
Date date = new Date();
// timestamp has to be in the same format as in database
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm:ss.SSS");
String formattedDate = sdf.format(date);
System.out.println("Current time: " + formattedDate);
// subtract desired time
if (msgOld.equals("hour")) {
date.setTime(date.getTime() - ONE_HOUR_MILLISCONDS);
formattedDate = sdf.format(date);
} else if (msgOld.equals("day")) {
date.setTime(date.getTime() - ONE_DAY_MILLISCONDS);
formattedDate = sdf.format(date);
}
这也很好 - 常量看起来像这样:final long ONE_HOUR_MILLISCONDS = 60 * 60 * 1000;
唯一的问题是我不知道如何在JDBC中编写查询。我试过这样做:
// prepare query
String query;
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
} else {
query = "DELETE FROM messages WHERE cur_timestamp < " + date + ";";
}
但它说我的SQL语句中有错误(第二个,TRUNCATE工作正常)。我也尝试在语句中添加formattedDate
而不是date
。
它有什么问题(可能是非常简单的事情 - 可能是java.util.Date
和SQL时间戳之间的差异......)?感谢您的任何提示!
// prepare query
String query;
PreparedStatement pstmt = null;
try {
if (msgOld.equals("all")) {
query = "TRUNCATE TABLE messages";
pstmt=conn.prepareStatement(query);
} else {
query = "DELETE FROM messages WHERE cur_timestamp < ?;";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, timestamp.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
try {
pstmt.execute();
System.out.println("Successfully deleted messages.");
pstmt.close();
} catch (Exception e) {
System.out.println("Error with db query.");
e.printStackTrace();
}
但是我仍然得到SQL异常(即使我将日期转换为时间戳并且喜欢这个Timestamp timestamp = new Timestamp(date.getTime());
并在satement中使用它)