java代码实现mysql数据库同步
时间: 2023-08-05 13:11:15 浏览: 168
可以使用Java中的JDBC(Java Database Connectivity)技术来实现MySQL数据库同步。以下是一个简单的示例代码:
```java
import java.sql.*;
public class MySQLSync {
public static void main(String[] args) {
String sourceURL = "jdbc:mysql://localhost:3306/source_db";
String targetURL = "jdbc:mysql://localhost:3306/target_db";
String username = "root";
String password = "password";
try {
// 连接源数据库
Connection sourceConnection = DriverManager.getConnection(sourceURL, username, password);
Statement sourceStatement = sourceConnection.createStatement();
// 连接目标数据库
Connection targetConnection = DriverManager.getConnection(targetURL, username, password);
Statement targetStatement = targetConnection.createStatement();
// 查询源数据库表
ResultSet resultSet = sourceStatement.executeQuery("SELECT * FROM source_table");
// 遍历查询结果并插入目标数据库表
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String insertQuery = "INSERT INTO target_table (id, name, age) VALUES (" + id + ", '" + name + "', " + age + ")";
targetStatement.executeUpdate(insertQuery);
}
System.out.println("MySQL database sync successful!");
// 关闭连接
resultSet.close();
sourceStatement.close();
sourceConnection.close();
targetStatement.close();
targetConnection.close();
} catch (SQLException e) {
System.out.println("MySQL database sync failed! Error message: " + e.getMessage());
}
}
}
```
以上代码仅作为示例,实际应用中需要根据具体需求进行修改。在实际应用中,还需要考虑多线程、增量同步等问题。
阅读全文