Java 获取数据库5分钟内新增数据 - 代码示例
以下是使用 Java 编写的获取数据库中某张表 5 分钟内新增数据的示例代码:
import java.sql.*;
import java.util.*;
public class GetNewDataInFiveMinutes {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name";
private static final String USER = "your_username";
private static final String PASS = "your_password";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Prepare a statement to retrieve the new data
String sql = "SELECT * FROM your_table_name WHERE created_at >= ?";
stmt = conn.prepareStatement(sql);
// Set the parameter for the time five minutes ago
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, -5);
Timestamp fiveMinutesAgo = new Timestamp(cal.getTimeInMillis());
stmt.setTimestamp(1, fiveMinutesAgo);
// Execute the query
rs = stmt.executeQuery();
// Process the result set
while(rs.next()) {
// Retrieve the data from the result set
int id = rs.getInt("id");
String name = rs.getString("name");
Timestamp createdAt = rs.getTimestamp("created_at");
// Print out the data
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Created at: " + createdAt);
System.out.println();
}
} catch(SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close resources
try {
if(rs != null) {
rs.close();
}
if(stmt != null) {
stmt.close();
}
if(conn != null) {
conn.close();
}
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Done.");
}
}
其中,需要将your_database_name、your_table_name、your_username和your_password替换为实际的数据库名称、表名称、用户名和密码。此外,该代码默认使用MySQL数据库,如果使用其他类型的数据库需要修改相应的JDBC驱动。
原文地址: https://www.cveoy.top/t/topic/mU50 著作权归作者所有。请勿转载和采集!