如何使用Java从mysql中获取最后2分钟的数据

时间:2018-03-07 12:01:01

标签: java mysql api

我需要使用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();
                }
            }
        }
    }

3 个答案:

答案 0 :(得分:0)

不要使用max(时间)而是使用now()

String qry = "SELECT * FROM test.api WHERE EndTime = date_sub(now(), interval 2 minute)";

答案 1 :(得分:0)

试试这个:

-- 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;

因此,您必须知道两次之间的时差并使用上面提出的相应查询。

DEMO

答案 2 :(得分:0)

     String qry = "SELECT * FROM test.api WHERE EndTime > date_sub(now(),interval 2 MINUTE) ";