sábado, 5 de noviembre de 2016

INSERTAR, MODIFICAR, ELIMINAR Y CONSULTAR DATOS CON C# Y MySQL

PRÁCTICA 17

INSERTAR, MODIFICAR, ELIMINAR Y CONSULTAR DATOS CON C# Y MySQL


Objetivo. Diseñar una aplicación que vincule C# con una base de datos en MySQL.
La aplicación deberá permitir insertar (Altas), modificar (Edición), eliminar (Bajas) y consultar registros en una base de datos de MySQL.

CÓDIGO
//BDcomun

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace practica_17
{
    public class BdComun
    {
        public static MySqlConnection ObtenerConexion()
        {
            MySqlConnection conectar = new MySqlConnection("server=127.0.0.1; database=practica17; uid=root; pwd=;");
            conectar.Open();
            return conectar;
        }
    }
}



//Buscar clientes

using System.Text;
using System.Windows.Forms;

namespace practica_17
{
    public partial class BuscarClientes : Form
    {
        public BuscarClientes()
        {
            InitializeComponent();
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = ClientesDAL.Buscar(txtNombre.Text, txtApellido.Text);
        }

        public Cliente ClienteSeleccionado { get; set; }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
                ClienteSeleccionado = ClientesDAL.ObtenerCliente(id);

                this.Close();
            }
            else
                MessageBox.Show("Debe seleccionar una fila", "Atencion", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}


//clientes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace practica_17
{
    public class Cliente
    {
        public int Id { get; set; }
        public string Nombre { get; set; }
        public string Apellido { get; set; }
        public string Fecha_Nac { get; set; }
        public string Direccion { get; set; }

        public Cliente() { }

        public Cliente(int pId, string pNombre, string pApellido, string pFecha_Nac, string pDireccion)
        {
            this.Id = pId;
            this.Nombre = pNombre;
            this.Apellido = pApellido;
            this.Fecha_Nac = pFecha_Nac;
            this.Direccion = pDireccion;
        }

    }
}


//Clientes DAL

namespace practica_17
{
    public class ClientesDAL
    {
        public static int Agregar(Cliente pCliente)
        {

            int retorno = 0;

            MySqlCommand comando = new MySqlCommand(string.Format("Insert into clientes (Nombre, Apellido, Fecha_Nacimiento, Direccion) values ('{0}','{1}','{2}', '{3}')",
                pCliente.Nombre, pCliente.Apellido, pCliente.Fecha_Nac, pCliente.Direccion), BdComun.ObtenerConexion());
            retorno = comando.ExecuteNonQuery();
            return retorno;
        }

        public static List<Cliente> Buscar(string pNombre, string pApellido)
        {
            List<Cliente> _lista = new List<Cliente>();

            MySqlCommand _comando = new MySqlCommand(String.Format(
           "SELECT IdCliente, Nombre, Apellido, Fecha_Nacimiento, Direccion FROM clientes  where Nombre ='{0}' or Apellido='{1}'", pNombre, pApellido), BdComun.ObtenerConexion());
            MySqlDataReader _reader = _comando.ExecuteReader();
            while (_reader.Read())
            {
                Cliente pCliente = new Cliente();
                pCliente.Id = _reader.GetInt32(0);
                pCliente.Nombre = _reader.GetString(1);
                pCliente.Apellido = _reader.GetString(2);
                pCliente.Fecha_Nac = _reader.GetString(3);
                pCliente.Direccion = _reader.GetString(4);


                _lista.Add(pCliente);
            }

            return _lista;

        }
        public static Cliente ObtenerCliente(int pId)
        {
            Cliente pCliente = new Cliente();
            MySqlConnection conexion = BdComun.ObtenerConexion();

            MySqlCommand _comando = new MySqlCommand(String.Format("SELECT IdCliente, Nombre, Apellido, Fecha_Nacimiento, Direccion FROM clientes where IdCliente={0}", pId), conexion);
            MySqlDataReader _reader = _comando.ExecuteReader();
            while (_reader.Read())
            {
                pCliente.Id = _reader.GetInt32(0);
                pCliente.Nombre = _reader.GetString(1);
                pCliente.Apellido = _reader.GetString(2);
                pCliente.Fecha_Nac = _reader.GetString(3);
                pCliente.Direccion = _reader.GetString(4);

            }

            conexion.Close();
            return pCliente;

        }

        public static int Actualizar(Cliente pCliente)
        {
            int retorno = 0;
            MySqlConnection conexion = BdComun.ObtenerConexion();

            MySqlCommand comando = new MySqlCommand(string.Format("Update clientes set Nombre='{0}', Apellido='{1}', Fecha_Nacimiento='{2}', Direccion='{3}' where IdCliente={4}",
                pCliente.Nombre, pCliente.Apellido, pCliente.Fecha_Nac, pCliente.Direccion, pCliente.Id), conexion);

            retorno = comando.ExecuteNonQuery();
            conexion.Close();

            return retorno;

        }

        public static int Eliminar(int pId)
        {
            int retorno = 0;
            MySqlConnection conexion = BdComun.ObtenerConexion();

            MySqlCommand comando = new MySqlCommand(string.Format("Delete From clientes where IdCliente={0}", pId), conexion);

            retorno = comando.ExecuteNonQuery();
            conexion.Close();

            return retorno;

        }


    }
}


//Base

namespace practica_17
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Deshabilitar();
        }
        

        public Cliente ClienteActual { get; set; }

        private void tlsGuardar_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtNombre.Text) || string.IsNullOrWhiteSpace(txtApellido.Text) ||
                            string.IsNullOrWhiteSpace(txtDireccion.Text))

                MessageBox.Show("Hay Uno o mas Campos Vacios", "Campos Vacios", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
            {
                Cliente pCliente = new Cliente();
                pCliente.Nombre = txtNombre.Text.Trim();
                pCliente.Apellido = txtApellido.Text.Trim();
                pCliente.Fecha_Nac = dtpFechaNacimiento.Value.Year + "/" + dtpFechaNacimiento.Value.Month + "/" + dtpFechaNacimiento.Value.Day;
                pCliente.Direccion = txtDireccion.Text.Trim();

                int resultado = ClientesDAL.Agregar(pCliente);
                if (resultado > 0)
                {
                    MessageBox.Show("Cliente Guardado Con Exito!!", "Guardado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Limpiar();
                    Deshabilitar();
                }
                else
                {
                    MessageBox.Show("No se pudo guardar el cliente", "Fallo!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

        }

        private void tlsBuscar_Click(object sender, EventArgs e)
        {
            BuscarClientes lali = new BuscarClientes();
            lali.ShowDialog();

            if (lali.ClienteSeleccionado != null)
            {
                ClienteActual = lali.ClienteSeleccionado;
                txtNombre.Text = lali.ClienteSeleccionado.Nombre;
                txtApellido.Text = lali.ClienteSeleccionado.Apellido;
                txtDireccion.Text = lali.ClienteSeleccionado.Direccion;
                dtpFechaNacimiento.Text = lali.ClienteSeleccionado.Fecha_Nac;
                tlsActualizar.Enabled = true;
                tlsEliminar.Enabled = true;
                Habilitar();
                tlsGuardar.Enabled = false;
                
            }
        }

        private void tlsActualizar_Click(object sender, EventArgs e)
        {
            Cliente pCliente = new Cliente();
            if (string.IsNullOrWhiteSpace(txtNombre.Text) || string.IsNullOrWhiteSpace(txtApellido.Text) ||
                            string.IsNullOrWhiteSpace(txtDireccion.Text))

                MessageBox.Show("Hay Uno o mas Campos Vacios", "Campos Vacios", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
            {
                pCliente.Nombre = txtNombre.Text.Trim();
                pCliente.Apellido = txtApellido.Text.Trim();
                pCliente.Fecha_Nac = dtpFechaNacimiento.Value.Year + "/" + dtpFechaNacimiento.Value.Month + "/" + dtpFechaNacimiento.Value.Day;
                pCliente.Direccion = txtDireccion.Text.Trim();
                pCliente.Id = ClienteActual.Id;

                if (ClientesDAL.Actualizar(pCliente) > 0)
                {
                    MessageBox.Show("Los datos del cliente se actualizaron", "Datos Actualizados", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Limpiar();
                    Deshabilitar();
                }
                else
                {
                    MessageBox.Show("No se pudo actualizar", "Error al Actualizar", MessageBoxButtons.OK, MessageBoxIcon.Hand);

                }
            }
        }

        private void tlsEliminar_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Esta Seguro que desea eliminar el Cliente Actual", "¿Estas Seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ClientesDAL.Eliminar(ClienteActual.Id) > 0)
                {
                    MessageBox.Show("¡Cliente Eliminado Correctamente!", "Cliente Eliminado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Limpiar();
                    Deshabilitar();
                }
                else
                {
                    MessageBox.Show("No se pudo eliminar el Cliente", "Cliente No Eliminado", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            else
                MessageBox.Show("Se cancelo la eliminacion", "Eliminacion Cancelada", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void tlsNuevo_Click(object sender, EventArgs e)
        {
            Limpiar();
            Habilitar();
        }

        void Limpiar()
        {
            txtNombre.Clear();
            txtApellido.Clear();
            txtDireccion.Clear();
            dtpFechaNacimiento.ResetText();

        }
        void Deshabilitar()
        {
            txtNombre.Enabled = false;
            txtApellido.Enabled = false;
            txtDireccion.Enabled = false;
            dtpFechaNacimiento.Enabled = false;
            tlsGuardar.Enabled = false;
            tlsEliminar.Enabled = false;
            tlsActualizar.Enabled = false;
            tlsCancelar.Enabled = false;

            tlsNuevo.Enabled = true;
        }
        void Habilitar()
        {
            txtNombre.Enabled = true;
            txtApellido.Enabled = true;
            txtDireccion.Enabled = true;
            dtpFechaNacimiento.Enabled = true;
            tlsGuardar.Enabled = true;
            tlsCancelar.Enabled = true;

        }

        private void tlsCancelar_Click(object sender, EventArgs e)
        {
            Limpiar();
            Deshabilitar();
        }


    }
}

ALUMNOS Y CALIFICACIONES

PRÁCTICA 16

ALUMNOS Y CALIFICACIONES


Objetivo. Diseñar una aplicación en C# que vincule con una base de datos de Access (con las tablas alumnos y calificaciones relacionadas).
La aplicación deberá insertar, consultar, actualizar y eliminar registros en la base de datos de Access.

CÓDIGO
namespace Practica_16
{
    class Alumnos
    {
        public string ncuenta;
        public string Nombre;
        public string Apellidop;
        public string Apellidom;
        public int Edad;
        public int Semestre;

        public Alumnos()
        {
        }

        public Alumnos(string ncuenta, string Nombre, string Apellidop, string Apellidom,
            int Edad, int Semestre)
        {
            this.ncuenta = ncuenta;
            this.Nombre = Nombre;
            this.Apellidop = Apellidop;
            this.Apellidom = Apellidom;
            this.Edad = Edad;
            this.Semestre = Semestre;
        }

    }
}


namespace Practica_16
{
    class Database
    {
        private string StrConexion;
        private OleDbConnection Conexion;
        private OleDbDataAdapter Adapter;
        private DataSet miDataSet = new DataSet();

        public void IniciarConexion(string DataBase)
        {
            //Crear la cadena de conexion para Office 2010
            StrConexion = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DataBase;
            //Objeto conexion
            Conexion = new OleDbConnection(StrConexion);

        }
        public int ejecutar_sql(string sql)
        {
            //insertar en la BD
            int i = 0;
            try
            {
                Conexion.Open();
                OleDbCommand cmd = new OleDbCommand(sql, Conexion);
                i = cmd.ExecuteNonQuery();
            }
            catch
            {
                i = -1;

            }
            return i;
        }
        public DataTable consultar(string sql, string tabla)
        {
            Adapter = new OleDbDataAdapter(sql, Conexion);
            //crear data table 
            DataTable dt = new DataTable();
            //rellenar el adaptador con los datos en memoria
            Adapter.Fill(dt);
            return dt;
        }
    }
}


namespace Practica_16
{
    public partial class Form1 : Form
    {
        Database DB = new Database();
        String sql;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            DB.IniciarConexion("../../prueba.mdb");
            //crear el miembro de datos del DataGridView
            dataGridView1.DataMember = "Alumnos";
        }

        private Alumnos asig_alum_text()
        {
            string ncuenta, Nombre, Apellidop, Apellidom;
            int edad = 0, semestre;
            ncuenta = txtCuenta.Text;
            Nombre = txtNombre.Text;
            Apellidop = txtApellidoP.Text;
            Apellidom=txtApellidoM.Text;
            try
            {
                edad = Convert.ToInt32(txtEdad.Text);
            }
            catch
            {
                MessageBox.Show("Ingrese un valor numerico");
                txtEdad.Focus();
                txtEdad.SelectionStart = 0;
                txtEdad.SelectionLength = txtEdad.TextLength;
            }
            semestre = Convert.ToInt32(txtSemestre.Text);
            Alumnos A = new Alumnos(ncuenta, Nombre, Apellidop, Apellidom, semestre, edad);
            return A;
        }

        private void btnInsertar_Click(object sender, EventArgs e)
        {
            Alumnos a = asig_alum_text();
            sql = "INSERT INTO Alumnos (ncuenta,Nombre,Apellidop,Apellidom,Semestre,Edad)";
            sql+= " VALUES('" + a.ncuenta+"'"+",'"+a.Nombre+"','"+a.Apellidop+"','"+a.Apellidom+"','"+
                a.Semestre+"','"+a.Edad+"')";
            int insert = DB.ejecutar_sql(sql);
            if (insert == 1) //si logro la insercion limpio el formulario
            {
                MessageBox.Show("Se  insertaron correctamente sus datos");
                /*foreach (Control txt in this.Controls)
                {
                    if (txt.GetType() == typeof(TextBox))
                        txt.Text = "";
                }*/
                txtCuenta.Text = "";
                txtNombre.Text = "";
                txtApellidoM.Text = "";
                txtApellidoP.Text = "";
                txtEdad.Text = "";
                txtSemestre.Text = "";
            }
            else
            {
                MessageBox.Show("Hubo un error al insertar los datos");
            }
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            sql = "SELECT * FROM Alumnos WHERE ncuenta='" + txtNcuenta.Text + "'";
            // Poner los datos al DataGridView
            dataGridView1.DataSource = DB.consultar(sql, "alumnos");

        }

        private void modificarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Para modificar los datos del alumno
            int renglon = dataGridView1.CurrentCell.RowIndex;
            int ncuenta=Convert.ToInt32(dataGridView1[0,renglon].Value.ToString());
            if (ncuenta != -1)
            {
                txtCuenta.Text = dataGridView1[0, renglon].Value.ToString();
                txtNombre.Text = dataGridView1[1, renglon].Value.ToString();
                txtApellidoP.Text = dataGridView1[2, renglon].Value.ToString();
                txtApellidoM.Text = dataGridView1[3, renglon].Value.ToString();
                txtEdad.Text = dataGridView1[4, renglon].Value.ToString();
                txtSemestre.Text = dataGridView1[5, renglon].Value.ToString();
                btnActualizar.Enabled = true;
            }
        }

        private void eliminarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Para eliminar un registro
            int renglon = dataGridView1.CurrentCell.RowIndex;
            int ncuenta = Convert.ToInt32(dataGridView1[0, renglon].Value.ToString());
            if (ncuenta != -1)
            {
                if (MessageBox.Show("¿Está seguro que desea eliminar al alumno? " + dataGridView1[1, renglon].Value.ToString(),
                  "Eliminar Registro", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    DB.ejecutar_sql("DELETE FROM alumnos WHERE ncuenta='" + ncuenta + "'");
                dataGridView1.Rows.RemoveAt(renglon);
                txtNcuenta.Text = "";
            }
        }

        private void btnActualizar_Click(object sender, EventArgs e)
        {
            Alumnos a = asig_alum_text();
            sql = "UPDATE alumnos SET nombre='" + a.Nombre + "',";
            sql += "Apellidop='" + a.Apellidop + "',";
            sql += "Apellidom='" + a.Apellidom + "',";
            sql += "Edad='" + a.Edad + "',";
            sql+="Semestre='"+a.Semestre+"'";
            sql+="WHERE ncuenta='"+a.ncuenta+"'";

            int update = DB.ejecutar_sql(sql);
            if (update == 1)
            {
                MessageBox.Show("Se actualizaron correctamente los datos");
                txtCuenta.Text = "";
                txtNombre.Text = "";
                txtApellidoM.Text = "";
                txtApellidoP.Text = "";
                txtEdad.Text = "";
                txtSemestre.Text = "";
            }
            else
            {
                MessageBox.Show("Hubo un error al insertar los datos");
            }
        }
    }
}