java定时实现数据抽取

https://www.cnblogs.com/niudaxianren/p/11077578.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Java 的 Timer 和 TimerTask 类来实现定时任务。 首先,你需要创建一个 Timer 对象,并使用它调度一个 TimerTask 对象,以便在指定的时间间隔内执行任务。在 TimerTask 中,你可以编写代码来抽取一张表的数据并插入到另一张表中。 以下是一个示例代码,可以每隔一分钟从表A中抽取数据并插入到表B中: ```java import java.sql.*; public class TableDataTransfer { private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; private static final String DB_URL = "jdbc:mysql://localhost:3306/"; private static final String USER = "root"; private static final String PASS = "password"; private static final String SOURCE_TABLE = "table_a"; private static final String DEST_TABLE = "table_b"; public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { Connection conn = null; Statement stmt = 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); // Execute a query to get data from source table System.out.println("Extracting data from source table..."); stmt = conn.createStatement(); String sql = "SELECT * FROM " + SOURCE_TABLE; ResultSet rs = stmt.executeQuery(sql); // Insert data into destination table System.out.println("Inserting data into destination table..."); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); String insertSql = "INSERT INTO " + DEST_TABLE + " (id, name, age) VALUES (" + id + ", '" + name + "', " + age + ")"; stmt.executeUpdate(insertSql); } // Clean-up environment rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { // Handle errors for JDBC se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName e.printStackTrace(); } finally { // Finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } // nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } // end finally try } } }; // Schedule the task to run every minute timer.schedule(task, 0, 60 * 1000); } } ``` 请注意,这只是一个基本示例代码,你需要根据实际情况进行修改和优化。例如,你可以添加异常处理、日志记录等功能来提高代码的健壮性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值