如何用java代码用jdbc每隔5秒从数据库中查询5秒前的数据
以下是使用Java代码使用JDBC每隔5秒从数据库中查询5秒前的数据的示例代码:
import java.sql.*;
import java.util.Date;
public class DBQuery {
public static void main(String[] args) throws Exception {
// Set up the database connection
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, user, password);
// Prepare the SQL statement
String sql = "SELECT * FROM mytable WHERE timestamp < ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
// Execute the query every 5 seconds
while (true) {
// Get the current time and subtract 5 seconds
long currentTime = new Date().getTime();
long fiveSecondsAgo = currentTime - 5000;
// Set the timestamp parameter in the SQL statement
pstmt.setTimestamp(1, new Timestamp(fiveSecondsAgo));
// Execute the query and process the results
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// Process each row of data
int id = rs.getInt("id");
String name = rs.getString("name");
Timestamp timestamp = rs.getTimestamp("timestamp");
System.out.println(id + " " + name + " " + timestamp);
}
// Wait for 5 seconds before executing the query again
Thread.sleep(5000);
}
}
}
在这个示例中,我们使用了JDBC连接到MySQL数据库,并准备了一个带有参数的SQL语句,其中我们将在每次查询中使用当前时间减去5秒钟的时间戳作为参数。我们使用一个while循环来执行查询,并在每次查询之间等待5秒钟,以确保每个查询都是5秒钟前的数据。我们使用ResultSet对象来处理查询结果,并在控制台上打印出每行数据的id、name和timestamp字段。
原文地址: https://www.cveoy.top/t/topic/biWP 著作权归作者所有。请勿转载和采集!