Insertar registros en MySQL (MariaDB) con C# [05]
En este tutorial vamos a insertar registros en MySQL (MariaDB) con C# en base a los diferentes campos que creamos.
- Insertamos tres TextBox y cada uno tendrá los campos de nuestra tabla.
- nombre.
- puesto.
- edad.
- Además insertamos un botón guardar que limpiara el dataGridView y realizar a una nueva consulta de todos los registros para que se muestre el registro insertado.
Codigo: https://github.com/programadornovato/MySQL-CSharp/commit/2c441e903917bc05ad4a9e38e00b374c587923ee
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQL_CSharp
{
public partial class Form1 : Form
{
MySqlConnection myCon;
public Form1()
{
InitializeComponent();
conectar();
llenarTabla();
}
private void conectar() {
try
{
string server = "localhost";
string database = "empleados";
string user = "root";
string pwd = "123456";
string cadenaConexion = "server=" + server + ";database=" + database + ";" + "Uid=" + user + ";pwd=" + pwd + ";";
myCon = new MySqlConnection(cadenaConexion);
myCon.Open();
lblResultado.Text = "Conexion exitosa";
}
catch (Exception error)
{
lblResultado.Text = "Error de conexion " + error;
}
}
private void llenarTabla() {
string query = "select id,nombre,puesto,edad from trabajadores;";
MySqlCommand comandoDB = new MySqlCommand(query, myCon);
comandoDB.CommandTimeout = 60;
MySqlDataReader reader;
try
{
reader = comandoDB.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int n = dgTrabajadores.Rows.Add();
dgTrabajadores.Rows[n].Cells[0].Value = reader.GetString(0);
dgTrabajadores.Rows[n].Cells[1].Value = reader.GetString(1);
dgTrabajadores.Rows[n].Cells[2].Value = reader.GetString(2);
dgTrabajadores.Rows[n].Cells[3].Value = reader.GetString(3);
//MessageBox.Show(reader.GetString(0));
}
}
else
{
Console.WriteLine("No hay trabajadores");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void btnBuscar_Click(object sender, EventArgs e)
{
string where = " where 1=1 ";
//Si el nombre no esta vacio
if (txtBusNombre.Text != "")
{
where = where + " and nombre like'%" + txtBusNombre.Text + "%' ";
}
//Si el puesto no esta vacio
if (txtBusPuesto.Text != "")
{
where = where + " and puesto like'%" + txtBusPuesto.Text + "%' ";
}
//Si la edad no esta vacio
if (txtBusEdad.Text != "")
{
where = where + " and edad like'%" + txtBusEdad.Text + "%' ";
}
string query = "select id,nombre,puesto,edad from trabajadores " + where + " ;";
MySqlCommand comandoDB = new MySqlCommand(query, myCon);
comandoDB.CommandTimeout = 60;
MySqlDataReader reader;
dgTrabajadores.Rows.Clear();
dgTrabajadores.Refresh();
try
{
reader = comandoDB.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
int n = dgTrabajadores.Rows.Add();
dgTrabajadores.Rows[n].Cells[0].Value = reader.GetString(0);
dgTrabajadores.Rows[n].Cells[1].Value = reader.GetString(1);
dgTrabajadores.Rows[n].Cells[2].Value = reader.GetString(2);
dgTrabajadores.Rows[n].Cells[3].Value = reader.GetString(3);
//MessageBox.Show(reader.GetString(0));
}
}
else
{
Console.WriteLine("No hay trabajadores");
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void btnInsertar_Click(object sender, EventArgs e)
{
string query = "";
string mensajeError = "";
if (txtInNombre.Text == "") {
mensajeError = mensajeError + "El nombre no puede estar vacio";
}
if (txtInPuesto.Text == "") {
mensajeError = mensajeError + "El puesto no puede estar vacio";
}
if (txtInEdad.Text == "") {
mensajeError = mensajeError + "La edad no puede estar vacio";
}
if (mensajeError == "")
{
query = "insert into trabajadores " +
"(nombre ,puesto ,edad) values " +
"('" + txtInNombre.Text + "','" + txtInPuesto.Text + "','" + txtInEdad.Text + "')";
MySqlCommand comando = new MySqlCommand(query, myCon);
comando.CommandTimeout = 60;
MySqlDataReader reader;
try
{
reader = comando.ExecuteReader();
reader.Close();
dgTrabajadores.Rows.Clear();
dgTrabajadores.Refresh();
llenarTabla();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
else {
MessageBox.Show(mensajeError);
}
}
}
}
🎦 [CURSO] C##️⃣: https://www.youtube.com/watch?v=NKPMGY6NCko&list=PLCTD_CpMeEKQSOU8Vf9VHXrZa2rc8X0X5&index=1&t=3s&ab_channel=programadornovatoprogramadornovato
🎦 [CURSO] C CON FORMULARIOS##️⃣: https://www.youtube.com/watch?v=l0_U4oyOuns&list=PLCTD_CpMeEKTBih1VgeunCjc83ZQ6UBMI&index=1&ab_channel=programadornovatoprogramadornovato
🎦 [CURSO] C++ DE 0 A HEROE 🦸: https://www.youtube.com/watch?v=APN8aCyPvww&list=PLCTD_CpMeEKTofxs7iottRxJ5YPM7BOcc&ab_channel=programadornovato
🎦 [Curso] Java Netbeans GUI Completo☕: https://www.youtube.com/watch?v=18UA7X2ss8g&list=PLCTD_CpMeEKThfXo8D-RXOGu5FarO7_qv&ab_channel=programadornovato
Anterior tutorial Siguiente tutorial