简体   繁体   中英

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);
    }      
}

}

Sadly I don't quite follow your code as I don't know the function names, however yes you can have two or more connections to MySQL open.

To synchronize the data is a tricky one, if you want to do a one-way synch then this wouldn't be difficult to do, but if you wanted a two way then you would have to handle a lot of exceptions for when there is duplicate data.

If you want to get data from local database to a remote database then something like this would work:

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();
        }
    }
}

sorry it's untested and may have coding errors as I'm not infront of VS to test

You can write DML statements (INSERT's, UPDATE's, DELETE's) to merge two tables on the same server, and then execute them.

If you want to synchronize tables on two different servers, then you should read data from tables, analyze data it in the application, and then generate synchronization script. I can say this task seems to be difficult.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM