用.net写一个mysql数据迁移代码
时间: 2024-01-26 12:04:44 浏览: 24
好的,以下是使用 C# 语言和 MySQL 数据库的迁移代码示例:
```csharp
using System;
using MySql.Data.MySqlClient;
class Program {
static void Main(string[] args) {
string sourceConnectionString = "server=source_server;user=source_user;password=source_password;database=source_database;";
string targetConnectionString = "server=target_server;user=target_user;password=target_password;database=target_database;";
MySqlConnection sourceConnection = new MySqlConnection(sourceConnectionString);
MySqlConnection targetConnection = new MySqlConnection(targetConnectionString);
try {
sourceConnection.Open();
targetConnection.Open();
MySqlCommand sourceCommand = new MySqlCommand("SELECT * FROM source_table", sourceConnection);
MySqlDataReader reader = sourceCommand.ExecuteReader();
while (reader.Read()) {
int id = reader.GetInt32(0);
string name = reader.GetString(1);
int age = reader.GetInt32(2);
MySqlCommand targetCommand = new MySqlCommand("INSERT INTO target_table (id, name, age) VALUES (@id, @name, @age)", targetConnection);
targetCommand.Parameters.AddWithValue("@id", id);
targetCommand.Parameters.AddWithValue("@name", name);
targetCommand.Parameters.AddWithValue("@age", age);
targetCommand.ExecuteNonQuery();
}
reader.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
} finally {
sourceConnection.Close();
targetConnection.Close();
}
}
}
```
以上代码将从源 MySQL 数据库中的 `source_table` 表中读取数据,并将其迁移到目标 MySQL 数据库中的 `target_table` 表中。请注意,您需要将代码中的连接字符串、源表和目标表按实际情况进行修改。