Java 跨服务器将一个库的表数据同步到另一个库 demo
时间: 2023-08-04 11:05:04 浏览: 92
服务器之间数据库同步
下面是一个简单的 Java demo,演示如何跨服务器将一个库的表数据同步到另一个库:
```java
import java.sql.*;
public class DataSyncDemo {
public static void main(String[] args) {
// 源库连接信息
String srcUrl = "jdbc:mysql://localhost:3306/src_db";
String srcUser = "root";
String srcPassword = "123456";
// 目标库连接信息
String destUrl = "jdbc:mysql://192.168.1.100:3306/dest_db";
String destUser = "admin";
String destPassword = "password";
// 表名和字段名
String tableName = "users";
String[] columnNames = { "id", "name", "age" };
Connection srcConn = null;
Connection destConn = null;
Statement srcStmt = null;
PreparedStatement destStmt = null;
ResultSet rs = null;
try {
// 连接源库
srcConn = DriverManager.getConnection(srcUrl, srcUser, srcPassword);
srcStmt = srcConn.createStatement();
String sql = "SELECT * FROM " + tableName;
rs = srcStmt.executeQuery(sql);
// 连接目标库
destConn = DriverManager.getConnection(destUrl, destUser, destPassword);
destStmt = destConn.prepareStatement(
"INSERT INTO " + tableName + " (" + String.join(",", columnNames) + ") VALUES (?, ?, ?)"
);
// 遍历源库结果集,插入到目标库
while (rs.next()) {
for (int i = 0; i < columnNames.length; i++) {
destStmt.setObject(i + 1, rs.getObject(columnNames[i]));
}
destStmt.addBatch();
}
destStmt.executeBatch();
System.out.println("Data sync succeeded.");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
srcStmt.close();
destStmt.close();
srcConn.close();
destConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这个 demo 连接了两个 MySQL 数据库,将源库中的 `users` 表同步到了目标库中。需要根据实际情况修改连接信息、表名和字段名等。
阅读全文