Mysql,sqllite表结构对比
本代码用C#实现,对比有差异的字段 ,调用类方法Comare 即可获取结果。
public class CompareDataBaseHelper
{
string mysqlConnectionString = "Server=127.0.0.1;Database=testdb;Uid=root;Pwd=123456;charset=utf8;";
string sqliteConnectionString = "Data Source=testdb.db;Version=3;";
//表名称
List<string> tableNames = new List<string>
{
"sutdent", "school"
};
public void Comare()
{
foreach (var tableName in tableNames)
{
Console.WriteLine($"Comparing table: {tableName}");
var mysqlColumns = GetMysqlColumns(mysqlConnectionString, tableName);
var sqliteColumns = GetSqliteColumns(sqliteConnectionString, tableName);
CompareColumns(mysqlColumns, sqliteColumns, tableName);
Console.WriteLine();
}
}
static Dictionary<string, string> GetMysqlColumns(string connectionString, string tableName)
{
var columns = new Dictionary<string, string>();
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var command = new MySqlCommand($"SHOW COLUMNS FROM {tableName}", connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var columnName = reader["Field"].ToString();
var columnType = reader["Type"].ToString();
columns[columnName] = columnType;
}
}
}
return columns;
}
static Dictionary<string, string> GetSqliteColumns(string connectionString, string tableName)
{
var columns = new Dictionary<string, string>();
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
var command = new SQLiteCommand($"PRAGMA table_info({tableName})", connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var columnName = reader["name"].ToString();
var columnType = reader["type"].ToString();
columns[columnName] = columnType;
}
}
}
return columns;
}
static void CompareColumns(Dictionary<string, string> mysqlColumns, Dictionary<string, string> sqliteColumns, string tableName)
{
Console.WriteLine($"Comparing columns for table: {tableName}");
foreach (var column in mysqlColumns)
{
if (sqliteColumns.TryGetValue(column.Key, out var sqliteType))
{
if (column.Value != sqliteType)
{
// Console.WriteLine($"Column {column.Key}: MySQL Type = {column.Value}, SQLite Type = {sqliteType}");
}
}
else
{
Console.WriteLine($"Column {column.Key} Type = {column.Value} exists in MySQL but not in SQLite.");
}
}
foreach (var column in sqliteColumns)
{
if (!mysqlColumns.ContainsKey(column.Key))
{
Console.WriteLine($"Column {column.Key} Type = {column.Value} exists in SQLite but not in MySQL.");
}
}
}
}