English 中文(简体)
如何能同时打开两个连接 来同步两个数据库
原标题:How I can have two connections open at once to synchronize two databases mysql in c#?

Hi all! I m trying to synchronize two databases, one local and one remote. The problem is that I have two connections open at once and do not know how. If the two databases I have them locally if I correctly updated because they use the same connection. The problem I have is that the local board to update the program does not see it because the connection is not open, how I can do? This is my code. Two databases have the same table estructure but user/pass and different database name. Thank you!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace sincronizacion
{
public partial class Form1 : Form
{
    private string stringConexionLocal ="server=localhost;database=kiosco_m;UID=root;pwd=toor";
    private string stringConexionRemota = "server="ipserverremote";database=grupoorb_kioscom;UID=user_remote;pwd=pass_remote";

    //Instanciado de objetos conexión local
    MySqlConnection conexionLocal;
    MySqlDataAdapter dataAdapterLocal;
    DataSet dataSetLocal;
    MySqlCommandBuilder builderLocal;

    //Instanciado de objetos conexión remota
    MySqlConnection conexionRemota;
    MySqlDataAdapter dataAdapterRemota;
    DataSet dataSetRemoto;
    MySqlCommandBuilder builderRemoto;

    public Form1()
    {
        InitializeComponent();
    时 时

    private void CargarDatosLocal()
    {
        string Consulta = "SELECT * FROM empresas";
        try
        {
            conexionLocal = new MySqlConnection(this.stringConexionLocal);
            dataAdapterLocal = new MySqlDataAdapter(Consulta, conexionLocal);
            dataSetLocal = new DataSet();
            dataAdapterLocal.Fill(dataSetLocal, "empresas");
            builderLocal = new MySqlCommandBuilder(dataAdapterLocal);
            dataGridView1.DataSource = dataSetLocal;
            dataGridView1.DataMember = "empresas";
        时 时
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message, "Error al intentar conectarse a la BBDD local.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        时 时

    时 时

    private void CargarDatosRemoto()
    {
        string Consulta = "SELECT * FROM empresas";
        try
        {
            conexionRemota = new MySqlConnection(this.stringConexionRemota);
            dataAdapterRemota = new MySqlDataAdapter(Consulta, conexionRemota);
            dataSetRemoto = new DataSet();
            dataAdapterRemota.Fill(dataSetRemoto, "empresas");
            builderRemoto = new MySqlCommandBuilder(dataAdapterRemota);
            dataGridView2.DataSource = dataSetRemoto;
            dataGridView2.DataMember = "empresas";

        时 时
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message, "Error al intentar conectarse a la BBDD Remota.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        时 时

    时 时

    private void Sincronizar(string miConexionRemota)
    {
        MySqlConnection miConexion = new MySqlConnection(miConexionRemota);
        miConexion.Open();
        MySqlCommand comando = new MySqlCommand();
        MySqlTransaction transaccion;

        // Empieza la transacción
        transaccion = miConexion.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        comando.Transaction = transaccion;
        comando.Connection = miConexion;

        try
        {
            comando.CommandText = "UPDATE kiosco_remoto.empresas INNER JOIN kiosco_m.empresas ON kiosco_remoto.empresas.Id = kiosco_m.empresas.Id SET kiosco_remoto.empresas.direccion = kiosco_m.empresas.direccion";
            comando.ExecuteNonQuery();
            transaccion.Commit();
            MessageBox.Show("Se han sincronizado las BBDD correctamente.", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
        时 时
        catch (MySqlException ex)
        {
            transaccion.Rollback();
            MessageBox.Show(ex.Message, "Error al intentar sincronizar.", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //throw ex;

        时 时
        finally
        {
            CargarDatosLocal();
            CargarDatosRemoto();
            miConexion.Close();
        时 时

    时 时

    /* * *
     * 
     * Eventos
     *
     * * */

    private void botonLocal_Click(object sender, EventArgs e)
    {
        CargarDatosLocal();
    时 时

    private void botonCargaDatosRemoto_Click(object sender, EventArgs e)
    {
        CargarDatosRemoto();
    时 时

    private void botonGrabarBDLocal_Click(object sender, EventArgs e)
    {
        try
        {
            builderLocal.GetUpdateCommand();
            dataAdapterLocal.Update(dataSetLocal, "empresas");
            CargarDatosLocal();
        时 时
        catch (NullReferenceException ex)
        {
            MessageBox.Show(ex.Message, "No hay ninguna BBDD abierta.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        时 时
    时 时

    private void botonGrabarBDRemota_Click(object sender, EventArgs e)
    {
        try
        {
            builderRemoto.GetUpdateCommand();
            dataAdapterRemota.Update(dataSetRemoto, "empresas");
            CargarDatosRemoto();
        时 时
        catch (NullReferenceException ex)
        {
            MessageBox.Show(ex.Message, "No hay ninguna BBDD abierta.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        时 时
    时 时

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        try
        {
            conexionLocal.Close();
            conexionRemota.Close();

            if ((conexionLocal != null) || (conexionRemota != null))
            {
                MessageBox.Show("Se han cerrado todas las conexiones abiertas.", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
            时 时
        时 时
        catch
        {
            // No hago nada.
        时 时
    时 时

    private void botonSincro_Click(object sender, EventArgs e)
    {
        Sincronizar(stringConexionRemota);
    时 时      
时 时

时 时

最佳回答

可惜我不太了解您的代码,因为我不知道函数名称, 但是您可以打开两个或两个以上的与 MySQL 的连接。

同步数据是一个棘手的问题, 如果你想做单向同步的话, 这样做并不困难, 但是如果你想用两种方式, 那么当数据重复时, 您将不得不处理很多例外 。

如果您想要从本地数据库获取数据到远程数据库, 类似的东西会有效 :

string const query = "SELECT * FROM LocalTableName";
using (DbCommand sql =_MySQLConnection.CreateCommand()){
    sql.CommandText = query;
    using (DbDataReader row = sql.ExecuteReader()){
        // the data is sstored in row now upload to remote
        using (DbCommand sql_remote = _MySQLRemote.CreateCommand()){
            sql_remote.CommandText = "INSERT INTO RemoteTableName SET field1 = @p_field1";
            sql.Parameters.Add("@p_field1", row["field1"].toString());
            sql.ExecuteNonQuery();
            sql.Parameters.Clear();
        }
    }
}

抱歉它未经测试, 并可能有编码错误, 因为我不是在 VS 前测试的 VS

问题回答

您可以写入 DML 语句( INSTERs, 更新后, DELTEs), 以合并同一服务器上的两个表格, 然后执行 。

如果您想要同步两个不同服务器上的表格, 那么您应该从表格中读取数据, 在应用程序中分析数据, 然后生成同步脚本 。 我可以说这任务似乎很难 。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签