java实现mysql同步_Java实现Mysql数据同步
时间: 2023-12-06 17:02:07 浏览: 39
Java 实现 Mysql 数据同步可以通过以下步骤实现:
1. 连接源数据库和目标数据库,获取连接对象;
2. 查询源数据库中需要同步的数据;
3. 将查询结果写入到目标数据库中;
4. 关闭连接对象。
具体的实现过程可以参考以下代码:
```
import java.sql.*;
public class MysqlSync {
public static void main(String[] args) {
Connection sourceConn = null;
Connection targetConn = null;
Statement sourceStmt = null;
Statement targetStmt = null;
ResultSet rs = null;
try {
// 连接源数据库
Class.forName("com.mysql.jdbc.Driver");
sourceConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/source_db", "root", "password");
sourceStmt = sourceConn.createStatement();
// 查询源数据库中需要同步的数据
rs = sourceStmt.executeQuery("SELECT * FROM source_table");
// 连接目标数据库
targetConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/target_db", "root", "password");
targetStmt = targetConn.createStatement();
// 将查询结果写入到目标数据库中
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
targetStmt.executeUpdate("INSERT INTO target_table (name, age) VALUES ('" + name + "', " + age + ")");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接对象
try {
if (rs != null) {
rs.close();
}
if (sourceStmt != null) {
sourceStmt.close();
}
if (sourceConn != null) {
sourceConn.close();
}
if (targetStmt != null) {
targetStmt.close();
}
if (targetConn != null) {
targetConn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
这段代码是一个简单的示例,实际应用中需要根据具体需求进行改进和优化。同时,需要注意数据库连接的安全性和性能问题。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)