[英]Comparing sql dates gone wrong in java
我的代碼中有消息傳遞功能。 它是這樣的:一個用戶,比如說用戶 A,在星期一向用戶 B 發送了一條消息。 我們有兩種情況(用戶 B 在線/離線),但無論哪種情況,代碼都會寫入數據庫。 基本上,消息從用戶 A 傳輸到數據庫(獲取時間戳 (1)),然后反彈給用戶 B。現在用戶 B 在第二天,星期二登錄。 然后,代碼會將用戶 B 成功登錄時的時間戳 (2) 與用戶 A 發送時的時間戳 (1) 進行比較。
我打算這樣做:1)如果時間戳(1)小於或等於用戶 B 登錄的時間戳(2)(如上例中的星期一與星期二),則顯示“您有 n 條消息”以及消息他們自己,或者 2) 如果時間戳 (1) 大於用戶 B 登錄的時間戳 (2)(周二與周一),那么顯然 B 一定已經閱讀了這些消息 - 所以我們忽略它,只檢查他是否有任何更新的消息並為他展示。
為此,我制作了這段代碼,但它不起作用。 即使有新消息,它也不會返回任何內容。 我做錯了什么? 我確實懷疑我的日期比較是錯誤的。 時間戳 (1) 的列 - 當消息被發送時,在DATETIME
中。
public static String receiveMessage(String email) throws Exception {
String returnStatement = "";
Connection connection = null;
connection = establishConnection();
String queryCheck = "SELECT * from usersmessages WHERE receiver = ?";
PreparedStatement prepstate = connection.prepareStatement(queryCheck);
prepstate.setString(1, email);
ResultSet resultSet = prepstate.executeQuery();
while(resultSet.next()) {
//fine
String queryCheck_1 = "SELECT * from usersmessages WHERE senttime < DATE(NOW())";
PreparedStatement prepstate_1 = connection.prepareStatement(queryCheck_1);
ResultSet resultSet_1 = prepstate_1.executeQuery();
/* This means the message time is older than the login time */
if(resultSet_1.next()) {
System.out.println("check");
String queryCheck_2 = "SELECT COUNT(*) from usersmessages WHERE senttime < DATE(NOW())";
PreparedStatement prepstate_2 = connection.prepareStatement(queryCheck_1);
ResultSet resultSet_2 = prepstate_1.executeQuery();
int messagecount = resultSet_2.getInt(1);
returnStatement = "You have " + messagecount + "new messages.";
for(int i = 0; i < messagecount; i++) {
returnStatement += "Message " + i + ":\n" + resultSet_2.getString(3);
}
}
}
return returnStatement;
}
編輯:我在數據庫中有 4 列。 在這里,它們與類型一起:
您正在查找接收者的消息,然后在您再次掃描所有消息的位置迭代結果(與接收者無關)。
您可以將第一個查詢更改為以下內容:-
String queryCheck = "SELECT * from usersmessages WHERE receiver = ? and senttime < DATE(NOW()) and isSeen=false";
然后迭代結果以計算新消息並顯示。 此外,您需要將消息 isSeen 標志標記為 true,否則當用戶下次登錄時,消息將再次出現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.