用java写一个mysql数据迁移代码
时间: 2024-03-02 17:48:46 浏览: 35
好的,以下是使用Java语言和MySQL数据库的迁移代码示例:
```java
import java.sql.*;
public class MysqlMigration {
public static void main(String[] args) {
String sourceUrl = "jdbc:mysql://source_server/source_database";
String sourceUser = "source_user";
String sourcePassword = "source_password";
String targetUrl = "jdbc:mysql://target_server/target_database";
String targetUser = "target_user";
String targetPassword = "target_password";
Connection sourceConnection = null;
Connection targetConnection = null;
try {
sourceConnection = DriverManager.getConnection(sourceUrl, sourceUser, sourcePassword);
targetConnection = DriverManager.getConnection(targetUrl, targetUser, targetPassword);
Statement sourceStatement = sourceConnection.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");
PreparedStatement targetStatement = targetConnection.prepareStatement("INSERT INTO target_table (id, name, age) VALUES (?, ?, ?)");
targetStatement.setInt(1, id);
targetStatement.setString(2, name);
targetStatement.setInt(3, age);
targetStatement.executeUpdate();
}
resultSet.close();
sourceStatement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (sourceConnection != null) {
sourceConnection.close();
}
if (targetConnection != null) {
targetConnection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
以上代码将从源MySQL数据库中的 `source_table` 表中读取数据,并将其迁移到目标MySQL数据库中的 `target_table` 表中。请注意,您需要将代码中的连接URL、用户名、密码、源表和目标表按实际情况进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)