C#同步两个数据库中两张表的数据

从Mysql两个数据库中同步表数据

先上需要的实体类

public class ServerConnectInfo
{
    public string SERVER { get; set; }
    
    public string DATABASE { get; set; }
    
    public string UID { get; set; }

    public string PWD { get; set; }

}

用到的方法

 public static void SynchronizationTable(ServerConnectInfo sourseInfo, ServerConnectInfo targetInfo,string tableName)
 {
     try
     {
         //获得原始表结构
         DataTable dtSourseInfoTable = new DataTable();
         dtSourseInfoTable = DatabaseHelper.GetTableColumnsName(sourseInfo, tableName);
         string sql = "select ";
         foreach (DataRow item in dtSourseInfoTable.Rows)
         {
             sql += string.Format("CONCAT('',{0}) as {1},", item["Field"].ToString(), item["Field"].ToString());
         }
         sql = sql.Trim(',');
         sql += " from  "+ tableName;

         if (dtSourseInfoTable == null && dtSourseInfoTable.Columns.Count <= 0)
         {
             return ;
         }

         //获得原始表数据
         dtSourseInfoTable = new DataTable();
         dtSourseInfoTable = DatabaseHelper.GetTable(sourseInfo, sql);
         if (dtSourseInfoTable == null && dtSourseInfoTable.Columns.Count <=0)
         {
             return ;
         }

         //删除目标库的表数据
         bool result = DatabaseHelper.DeleteTable(targetInfo);
         if (!result)
         {
             return ;
         }
         
         //向目标库插入数据
         string insertStr = DataTableToInsertSql(dtSourseInfoTable, tableName);

         bool insertResult = DatabaseHelper.Insert(targetInfo, insertStr);

         if (!insertResult)
         {
             return ;
         }
     }
     catch
     {
         return ;
     }

 }


public static string DataTableToInsertSql1(DataTable dt, string table)
{
    string result = "";
    string cols = string.Join(",", dt.Columns.Cast().Select(x => $"{x.ColumnName}").ToArray());
    result = $"insert into {table} ({cols}) values ";
    foreach (DataRow dr in dt.Rows)
    {
        var vals = "(";
        vals += string.Join(",", dr.ItemArray.Select(x =>
        {
            if (DBNull.Value.GetType() == x.GetType())
            {
                return "null";
            }
            else
            {
                return $"'{x}'";
            }
        }).ToArray());
        vals += "),";
        result += vals;
    }
    result = result.Trim(',');
    return result;
}

mysql DatabaseHelper 帮助类

       public static bool DeleteTable(ServerConnectInfo info)
       {
           string connectionString = string.Format("Allow Zero Datetime=True;database={0};server={1};uid={2};charset=utf8;pwd={3}", info.DATABASE, info.SERVER, info.UID, info.PWD);
           using (MySqlConnection mySqlConnection = new MySqlConnection(connectionString))
           {
               try
               {
                   mySqlConnection.Open();
                   MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
                   mySqlCommand.CommandText = "DELETE FROM cinema_info_report ";
                   mySqlCommand.CommandType = CommandType.Text;
                   int a = mySqlCommand.ExecuteNonQuery();
                   if (a >= 0)
                   {
                       return true;
                   }
               }
               catch (MySqlException ex)
               {
               }
               finally
               {
                   mySqlConnection.Close();
               }
           }
           return false;
       }


  public static DataTable GetTable(ServerConnectInfo info, string sql)
  {
      string connectionString = string.Format("Allow Zero Datetime=True;database={0};server={1};uid={2};charset=utf8;pwd={3}", info.DATABASE, info.SERVER, info.UID, info.PWD);
      using (MySqlConnection mySqlConnection = new MySqlConnection(connectionString))
      {
          try
          {
              mySqlConnection.Open();
              MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
              mySqlCommand.CommandText = @sql;
              mySqlCommand.CommandType = CommandType.Text;
              MySqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
              DataTable dt = new DataTable();
              dt.Load(mySqlDataReader);
              return dt;
          }
          catch (MySqlException ex)
          {
          }
          finally
          {
              mySqlConnection.Close();
          }
      }
      return null;
  }



  public static bool Insert(ServerConnectInfo info, string strSql)
  {
      string connectionString = string.Format("Allow Zero Datetime=True;database={0};server={1};uid={2};charset=utf8;pwd={3}", info.DATABASE, info.SERVER, info.UID, info.PWD);
      using (MySqlConnection mySqlConnection = new MySqlConnection(connectionString))
      {
          try
          {
              mySqlConnection.Open();
              MySqlCommand mySqlCommand = mySqlConnection.CreateCommand();
              mySqlCommand.CommandText = strSql;
              mySqlCommand.CommandType = CommandType.Text;

              int a = mySqlCommand.ExecuteNonQuery();
              if (a > 0)
              {
                  return true;
              }
          }
          catch (MySqlException)
          {
          }
          finally
          {
              mySqlConnection.Close();
          }
      }
      return false;
  }

使用示例

将ipA库的table_name表数据 每十分钟一次同步到ipB库的table_name表中

 static void Main(string[] args)
 {  
     Timer t = new Timer();
     t.Elapsed += new ElapsedEventHandler(SynchronizationEvent);
     t.Interval = 600000;
     t.Enabled = true;
     Console.Read();

 }


 public static void SynchronizationEvent(object source, System.Timers.ElapsedEventArgs e)
 {
     ServerConnectInfo sourseinfo = new ServerConnectInfo() { SERVER = "数据库ipA", DATABASE = "数据库名A", UID = "数据库账号A", PWD = "密码A" };
     ServerConnectInfo targetinfo = new ServerConnectInfo() { SERVER = "数据库ipB", DATABASE = "数据库名B", UID = "数据库账号B", PWD = "密码B" };//目标库账号要有写权限
     string tableName = "table_name";
     SynchronizationTable(sourseinfo, targetinfo, tableName);
 }

你可能感兴趣的:(C#,数据库,c#,开发语言)