I am currently trying to make a query run on a remote (school) database by means of a button and at the same time with the data saved in the Data Table, the same are saved in my local database table.
this is my code for my button in c#:
private void button1_Click_2(object sender, EventArgs e)
{
// CADENA DE CONEXION A LA BASE DE DATOS
string cadenaConexion = "Database=dprn3u3; Data source=35.197.23.46; User Id=estudiante; Password=dprn3pass; SSL Mode=None";
MySqlConnection conexion, comando2,conexion3;
DataTable dt = new DataTable();
MySqlDataReader resultados;
MySqlCommand comand = null;
string cadena = "Database=vivero; Data source=localhost; User Id=root; Password=; SSL Mode=None";
conexion3 = new MySqlConnection(cadena);
try
{
// ESTABLECE LA CONEXION A LA BASE DE DATOS
conexion = new MySqlConnection(cadenaConexion);
comando2 = new MySqlConnection(cadenaConexion);
// CONSULTA SQL
MySqlCommand comandos = new MySqlCommand("SELECT planta, MONTH(fecha) AS mes, YEAR(fecha) AS year, SUM(cantidad) as cantidad, SUM(total) as total FROM ventas GROUP BY year,mes,planta;", conexion);
MySqlCommand mysql = new MySqlCommand("SELECT COUNT(*) FROM ventas;", comando2);
// DECIMOS EL TIPO DE CONSULTA
comandos.CommandType = CommandType.Text;
// ABRE LA CONEXION A LA BASE DE DATOS
conexion.Open();
comando2.Open();
conexion3.Open();
// REALIZA LA CONSULTA Y LA ALMACENA EN LA VARIABLE RESULTADO
resultados = comandos.ExecuteReader();
// CARGA LOS REGISTROS OBTENIDOS EN LA TABLA Y EN EL STATUSTRIP
dt.Load(resultados);
int contar = Convert.ToInt32(mysql.ExecuteScalar());
etiquetavalores.Text = contar.ToString() + " " + "registros";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
database.DataSource = dt;
foreach (DataRow registro in dt.Rows)
{
string especie = (string)registro["planta"];
int mesventa = (int)registro["mes"];
int yearventa = (int)registro["year"];
var cantidad = registro["cantidad"];
var total = registro["total"];
string consulta = string.Empty;
consulta = "INSERT INTO ventas VALUES ('" + especie + "','" + mesventa + "','" + yearventa + "','" + cantidad + "','" + total + "')";
comand = new MySqlCommand(consulta, new MySqlConnection("Database=vivero; Data source=localhost; User Id=root; Password=; SSL Mode=None"));
}
}
At the time of executing the code, it shows the data according to the Query that is made to the remote database, but when it does not save anything in my local database:
I hope you can guide me to know what my mistake is and likewise I thank you in advance for your help and your time.