[英]How to fetch last 2 minutes data from mysql using Java
我需要使用Java程序從MySQL數據庫檢索最后2分鍾的數據嗎? 我不知道如何編寫查詢以獲取特定時間間隔內的數據並引用很多,但是找不到正確的查詢? 有人可以幫我嗎?
下面是我的Java程序,它連接到MySQL數據庫,正在執行查詢,但是該查詢無法正常工作並引發SQLSyntaxErrorException。
public static void main(String[] args)
{
String qry = "SELECT * FROM test.api WHERE EndTime = SELECT max(time) - interval 2 minute";
String url = "jdbc:mysql://localhost:3306";
String user = "root";
String password = "root@123";
Connection conn = null;
try
{
conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(qry);
ResultSet rs = pstmt.executeQuery();
while(rs.next())
{
String Name = rs.getString("Name");
String time = rs.getString("EndTime");
System.out.println(time);
System.out.println(Name);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
if(conn != null)
{
try
{
conn.close();
System.out.println("---Connection closed successfully---");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
不要使用max(time),而要使用now()
String qry = "SELECT * FROM test.api WHERE EndTime = date_sub(now(), interval 2 minute)";
嘗試這個:
-- suppose your data source time coincides with your storage server time
-- so to get the time 2 minutes ago should be like
SELECT * FROM test.api WHERE EndTime >= now() - interval 2 minute;
-- suppose your data source time is 60 behind your storage server time
-- so to get the time 2 minutes ago should be like
SELECT * FROM test.api WHERE EndTime >= now() - interval (2 + 60) minute;
-- suppose your data source time is 60 infront of your storage server time
-- so to get the time 2 minutes ago should be like
SELECT * FROM test.api WHERE EndTime >= now() - interval (2 - 60) minute;
因此,您將必須知道兩個時間之間的時差,並使用上面建議的適當查詢。
String qry = "SELECT * FROM test.api WHERE EndTime > date_sub(now(),interval 2 MINUTE) ";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.