Click here to Skip to main content
15,890,512 members
Articles / Programming Languages / C#

Connect C# to MySQL

Rate me:
Please Sign up or sign in to vote.
4.90/5 (149 votes)
17 Nov 2009CPOL6 min read 1.9M   108.8K   254   141
Connect C# to MySQL using MySQL Connector/Net, Insert, Update, Select, Delete example, Backup and restore MySQL database from C# or .NET application
The purpose of this article is to show in a step by step manner how to use and connect C# with MySql using MySql Connect/NET. I will create simple examples about the DML (Insert, Update, Select, Delete) throughout the article to show how to query the database using C#, and in the end I will show you how to backup your database and save it in a .sql file from our application, and how to restore it back.

Getting Started

Downloading Connector/Net

First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website. In this article, I will use the Connector/NET version 6.1.

Creating the Database

Now let's create the database, and the table that we are going to query from our application later on.

From the command line, we start by creating the database:

C#
create database ConnectCsharpToMysql;

Then we select the database to use before creating the table:

C#
use ConnectCsharpToMysql;

And we create the table that we will query from our application:

SQL
create table tableInfo
(
id INT NOT NULL AUTO INCREMENT,
name VARCHAR(30),
age INT,
PRIMARY KEY(id)
);

Using the Code

Adding Reference and Creating the MySQL Connector DLL from the Project

Before we start writing the code, we need to add the mysql Reference in our project. To do so, we right click our project name, and choose Add Reference:

Image 1

Then we choose MySql.Data from the list:

AddReference 2

In order to use the application on other computers that don't have the connector installed, we will have to create a DLL from the reference. To do so, we right click the reference name in our project, and set the copy local to true in its properties:

Add dll

Creating the Class

It's always a better idea to create a new class for connecting to the database and to separate the actual code from the code that will access the database. This will help keep our code neat, easier to read and more efficient.

We will start by adding the MySql Connector library:

C#
//Add MySql Library
using MySql.Data.MySqlClient;

Then declaring and initializing the variables that we will use:

  • connection: will be used to open a connection to the database.
  • server: indicates where our server is hosted, in our case, it's localhost.
  • database: is the name of the database we will use, in our case it's the database we already created earlier which is connectcsharptomysql.
  • uid: is our MySQL username.
  • password: is our MySQL password.
  • connectionString: contains the connection string to connect to the database, and will be assigned to the connection variable.

Our class will look as follows:
(Empty methods will be filled later on in this article.)

C#
class DBConnect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    //Constructor
    public DBConnect()
    {
        Initialize();
    }

    //Initialize values
    private void Initialize()
    {
        server = "localhost";
        database = "connectcsharptomysql";
        uid = "username";
        password = "password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
		database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

    //open connection to database
    private bool OpenConnection()
    {
    }

    //Close connection
    private bool CloseConnection()
    {
    }

    //Insert statement
    public void Insert()
    {
    }

    //Update statement
    public void Update()
    {
    }

    //Delete statement
    public void Delete()
    {
    }

    //Select statement
    public List <string> [] Select()
    {
    }

    //Count statement
    public int Count()
    {
    }

    //Backup
    public void Backup()
    {
    }

    //Restore
    public void Restore()
    {
    }
}

Opening and Closing the Connection

We should always open a connection before querying our table(s), and close it right after we're done, to release the resources and indicate that this connection is no longer needed.
Opening and closing a connection to the database is very simple, however, it's always better to use exception handling before opening a connection or closing it, to catch the errors and deal with them.

C#
//open connection to database
private bool OpenConnection()
{
    try
    {
        connection.Open();
        return true;
    }
    catch (MySqlException ex)
    {
        //When handling errors, you can your application's response based 
        //on the error number.
        //The two most common error numbers when connecting are as follows:
        //0: Cannot connect to server.
        //1045: Invalid user name and/or password.
        switch (ex.Number)
        {
            case 0:
                MessageBox.Show("Cannot connect to server.  Contact administrator");
                break;

            case 1045:
                MessageBox.Show("Invalid username/password, please try again");
                break;
        }
        return false;
    }
}

//Close connection
private bool CloseConnection()
{
    try
    {
        connection.Close();
        return true;
    }
    catch (MySqlException ex)
    {
        MessageBox.Show(ex.Message);
        return false;
    }
}

Working with DML (Insert, Update, Select, Delete)

Usually, Insert, update and delete are used to write or change data in the database, while Select is used to read data.
For this reason, we have different types of methods to execute those queries.
The methods are the following:

  • ExecuteNonQuery: Used to execute a command that will not return any data, for example Insert, update or delete.
  • ExecuteReader: Used to execute a command that will return 0 or more records, for example Select.
  • ExecuteScalar: Used to execute a command that will return only 1 value, for example Select Count(*).

I will start with Insert, update and delete, which are the easiest. The process to successfully execute a command is as follows:

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.
  4. Execute the command.
  5. Close the connection.
C#
//Insert statement
public void Insert()
{
    string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";

    //open connection
    if (this.OpenConnection() == true)
    {
        //create command and assign the query and connection from the constructor
        MySqlCommand cmd = new MySqlCommand(query, connection);
        
        //Execute command
        cmd.ExecuteNonQuery();

        //close connection
        this.CloseConnection();
    }
}

//Update statement
public void Update()
{
    string query = "UPDATE tableinfo SET name='Joe', age='22' WHERE name='John Smith'";

    //Open connection
    if (this.OpenConnection() == true)
    {
        //create mysql command
        MySqlCommand cmd = new MySqlCommand();
        //Assign the query using CommandText
        cmd.CommandText = query;
        //Assign the connection using Connection
        cmd.Connection = connection;

        //Execute query
        cmd.ExecuteNonQuery();

        //close connection
        this.CloseConnection();
    }
}

//Delete statement
public void Delete()
{
    string query = "DELETE FROM tableinfo WHERE name='John Smith'";

    if (this.OpenConnection() == true)
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        cmd.ExecuteNonQuery();
        this.CloseConnection();
    }
}

To execute a Select statement, we add a few more steps, and we use the ExecuteReader method that will return a dataReader object to read and store the data or records.

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.
  4. Create a MySqlDataReader object to read the selected records/data.
  5. Execute the command.
  6. Read the records and display them or store them in a list.
  7. Close the data reader.
  8. Close the connection.
C#
//Select statement
public List< string >[] Select()
{
    string query = "SELECT * FROM tableinfo";

    //Create a list to store the result
    List< string >[] list = new List< string >[3];
    list[0] = new List< string >();
    list[1] = new List< string >();
    list[2] = new List< string >();

    //Open connection
    if (this.OpenConnection() == true)
    {
        //Create Command
        MySqlCommand cmd = new MySqlCommand(query, connection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader = cmd.ExecuteReader();
        
        //Read the data and store them in the list
        while (dataReader.Read())
        {
            list[0].Add(dataReader["id"] + "");
            list[1].Add(dataReader["name"] + "");
            list[2].Add(dataReader["age"] + "");
        }

        //close Data Reader
        dataReader.Close();

        //close Connection
        this.CloseConnection();

        //return list to be displayed
        return list;
    }
    else
    {
        return list;
    }
}

Sometimes, a command will always return only one value, like for example if we want to count the number of records, we have been using Select Count(*) from tableinfo;, in this case, we will have to use the method ExecuteScalar that will return one value.

The process to successfully run and ExecuteScalar is as follows:

  1. Open connection to the database.
  2. Create a MySQL command.
  3. Assign a connection and a query to the command. This can be done using the constructor, or using the Connection and the CommandText methods in the MySqlCommand class.
  4. Execute the command.
  5. Parse the result if necessary.
  6. Close the connection.
C#
//Count statement
public int Count()
{
    string query = "SELECT Count(*) FROM tableinfo";
    int Count = -1;

    //Open Connection
    if (this.OpenConnection() == true)
    {
        //Create Mysql Command
        MySqlCommand cmd = new MySqlCommand(query, connection);

        //ExecuteScalar will return one value
        Count = int.Parse(cmd.ExecuteScalar()+"");
        
        //close Connection
        this.CloseConnection();

        return Count;
    }
    else
    {
        return Count;
    }
}

Backup and Restore the Database

Before I show you how to backup the database from our application, I will explain a little bit about processes, commands, arguments and the input and output.
Usually, to backup a MySQL database from the command line, we write the following:

mysqldump -u username -p password -h localhost ConnectCsharpToMysql > "C:\Backup.sql"

and to restore it, we write:

mysql -u username -p password -h localhost ConnectCsharpToMysql < "C:\Backup.sql"

The following commands can be divided as such:

  • mysql and mysqldump are the filename or the executable file.
  • -u username -p password -h localhost are the arguments.
  • > "C:\Backup.sql" is where the output is directed.
  • < "C:\Backup.sql" is where the input is directed.

Now that we know how the command is divided, we can start implementing it in our application.

In C# and .NET applications, starting a process is easy. First we add the library:

C#
using System.Diagnostics;

Then we launch an application, such as Internet Explorer:

C#
Process.Start("IExplore.exe");

ProcessStartInfo is used in conjunction with Process, to setup the process before it starts.
For example, to start Internet Explorer with arguments, we write the following:

C#
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "IExplore.exe";
psi.Arguments = "www.codeproject.com";
Process.Start(psi);

To write our output to a file or read our input, we can use the RedirectStandardInput and RedirectStandardOutput properties in the ProcessStartInfo component to cause the process to get input from or return output to a file or other device. If we use the StandardInput or StandardOutput properties on the Process component, we must first set the corresponding value on the ProcessStartInfo property. Otherwise, the system throws an exception when we read or write to the stream.

Now back to our application, to backup the database, we will have to set the RedirectStandardOutput to true, and read the output from the process into a string and save it to a file.

C#
//Backup
public void Backup()
{
    try
    {
        DateTime Time = DateTime.Now;
        int year = Time.Year;
        int month = Time.Month;
        int day = Time.Day;
        int hour = Time.Hour;
        int minute = Time.Minute;
        int second = Time.Second;
        int millisecond = Time.Millisecond;

        //Save file to C:\ with the current date as a filename
        string path;
        path = "C:\\MySqlBackup" + year + "-" + month + "-" + day + 
	"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
        StreamWriter file = new StreamWriter(path);

        
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "mysqldump";
        psi.RedirectStandardInput = false;
        psi.RedirectStandardOutput = true;
        psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", 
			uid, password, server, database);
        psi.UseShellExecute = false;

        Process process = Process.Start(psi);

        string output;
        output = process.StandardOutput.ReadToEnd();
        file.WriteLine(output);
        process.WaitForExit();
        file.Close();
        process.Close();
    }
    catch (IOException ex)
    {
        MessageBox.Show("Error , unable to backup!");
    }
}

To restore the database, we read the .sql file and store it in a string, then set the RedirectStandardInput property to true, and write the input from the string to the process.

C#
//Restore
public void Restore()
{
    try
    {
        //Read file from C:\
        string path;
        path = "C:\\MySqlBackup.sql";
        StreamReader file = new StreamReader(path);
        string input = file.ReadToEnd();
        file.Close();

        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "mysql";
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = false;
        psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", 
			uid, password, server, database);
        psi.UseShellExecute = false;

        
        Process process = Process.Start(psi);
        process.StandardInput.WriteLine(input);
        process.StandardInput.Close();
        process.WaitForExit();
        process.Close();
    }
    catch (IOException ex)
    {
        MessageBox.Show("Error , unable to Restore!");
    }
}

Conclusion

In this article, I demonstrated how to connect C# to MySQL and query the tables using simple examples for the insert, update, delete and select statements.
Also, and because it's not widely available over the internet, I decided to demonstrate how to backup and restore a MySQL database from the C# application.

History

  • 17th November, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Takunda Chinowona31-Aug-22 0:56
Takunda Chinowona31-Aug-22 0:56 
GeneralMy vote of 5 Pin
Member 1532450815-Aug-21 0:25
Member 1532450815-Aug-21 0:25 
Questionerror: database.table doesn't exit Pin
Member 1513723721-Jun-21 3:15
Member 1513723721-Jun-21 3:15 
GeneralMy vote of 5 Pin
JohnWong63-Jun-21 23:29
JohnWong63-Jun-21 23:29 
QuestionI get error 1042 connecting to MYSQL on Azure. Any idea why? Pin
Member 902823025-Oct-20 19:01
Member 902823025-Oct-20 19:01 
AnswerMessage Closed Pin
20-Jun-21 18:53
marktoddy20-Jun-21 18:53 
QuestionHow to get the valus from the List<string> Select; method Pin
Member 147902772-Apr-20 3:01
Member 147902772-Apr-20 3:01 
GeneralMy vote of 5 Pin
Member 1200788924-Dec-18 5:55
Member 1200788924-Dec-18 5:55 
GeneralMy vote of 5 Pin
Guillermo_Rodriguez16-May-18 5:43
Guillermo_Rodriguez16-May-18 5:43 
PraiseMy Vote 5 Pin
Sanpath Sunggad26-Apr-18 19:36
Sanpath Sunggad26-Apr-18 19:36 
GeneralLess than perfect. Pin
Member 1369335812-Apr-18 7:48
Member 1369335812-Apr-18 7:48 
QuestionNo MySql.Data Found Pin
Mohammad Abbas1-Jan-18 23:01
Mohammad Abbas1-Jan-18 23:01 
Questionseparate logic from GUI Pin
Member 1353083319-Nov-17 23:43
Member 1353083319-Nov-17 23:43 
QuestionGreat Article Pin
Member 1328475016-Nov-17 21:54
Member 1328475016-Nov-17 21:54 
GeneralMy vote of 5 Pin
droumanet3-Oct-17 7:05
droumanet3-Oct-17 7:05 
Questionopen a local database (.db file) Pin
Member 106310125-Feb-17 13:32
Member 106310125-Feb-17 13:32 
AnswerRe: open a local database (.db file) Pin
Garth J Lancaster5-Feb-17 13:41
professionalGarth J Lancaster5-Feb-17 13:41 
QuestionCS0168 The variable 'ex' is declared but never used Pin
Enzo17-Jan-17 9:25
Enzo17-Jan-17 9:25 
Questionthank you sir Pin
Bryan Lim13-Jan-17 6:08
Bryan Lim13-Jan-17 6:08 
QuestionThank you Pin
Jim Franklin31-Dec-16 1:53
Jim Franklin31-Dec-16 1:53 
QuestionAnd it is still usefull Pin
Mycroft Holmes21-Nov-16 20:00
professionalMycroft Holmes21-Nov-16 20:00 
Questionejemplo completo de Microsoft C# Sharp 2015 y base de datos mysql - uso using MySql.Data.MySqlClient;= "MySql.Data.dll" Pin
Member 1259146618-Jun-16 11:29
Member 1259146618-Jun-16 11:29 
PROYECTO : AGENDA (C# version 2015 gratuita) - 18-JUN-2016
- TRATAMIENTO DE INFORMACION DE PERSONA EN UN SOLO TEXTO ENRIQUECIDO
- OPERACIONES BASICAS DE AGREGAR,CONSULTAR,MODIFICAR Y ELIMINAR REGISTRO
DE PERSONA.
Atentamente :
Manuel Fuentes Briones (Chile)
Manuel Fuentes Briones (Chile)
contacto56@yahoo.es
===========================================================
OBJETOS DE LA APLICACION :
=========================================
Form1 = FORMULARIO UNICO DE APLICACION
TextBox1 = ID
TextBox2 = NOMBRE DE PERSONA
TextBox3 = AQUI SE INGRESA STRING A BUSCAR EN EL RESPECTIVO ITEM DEL RICHTEXTBOX1 DE BASE DATOS
richTextBox1 = TEXTO ENRIQUECIDO DONDE ESTA TODA LA INFORMACION PERSONA
Buttom1 = BOTON PARA AGREGAR (GRABAR) LA INFORMACION QUE ESTA DE LA PERSONA
Buttom2 = SALE DE LA APLICACION
Buttom3 = BUSCA LA INFORMACION QUE ESTA EN TEXTBOX2 , LA MISMA QUE MUESTRA NOMBRE PERSONA
Buttom4 = DEJA VIGENTE PARA ACTUALIZAR O BORRAR LA INFORMACION DE LA PERSONA ELEGIDA EN DATAGRIDVIEW
Buttom5 = BOTON PARA ACTUALIZAR LA INFORMACION QUE ESTA DE LA PERSONA
Buttom6 = BUSCA ITEM ELEGIDO EN LOS CONTENIDOS DE LOS RICHTEXTBOX DE CADA PERSONA EN BASE DATOS
Buttom7 = ESTE BOTON ELIMINA EL REGISTRO DE LA PERSONA VIGENTE
Buttom8 = LIMPIA CAMPOS DEL FORMULARIO (CASI TODOS)
Combobox1 = ESTE COMBO MUESTRA LOS ITEMS DEL RICHTEXTBOX1 PARA SELECCIONAR LA RESPECTIVA BUSQUEDA
DataGridView1 = AQUI DESPLIEGO TODA LA INFORMACION DE BUSQUEDAS , SE COMPLEMENTA CON BUTTOM4
Lebel1 = SOLO INFORMA QUE LA CONEXION CON BASE DE DATOS ESTA CORRECTA (OK)
DateTimePicker1 = SOLO PARA MOSTRARLO EN EL FORMULARIO
==========================
IMPORTANTE, AGREGAR REFERENCIA :
================================
Proyect ---> Add Reference --> Browser -->
C:\Program Files\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5
aqui elegir = "MySql.Data.dll" , para agregar al proyecto
o semejante , elegí al azar entro otros.
==============================

FORM1 :
--------
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;

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

private void button1_Click(object sender, EventArgs e)
{

if (textBox2.Text == "")
{
MessageBox.Show("NO puede AGREGAR ,debe escribir al menos Nombre", "Puede llenar campos o LIMPIAR Todo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{


Persona pPersona = new Persona();

pPersona.Nombre = textBox2.Text.ToString();
pPersona.Info = richTextBox1.Text.ToString();


int resultado = PersonasDAL.Agregar(pPersona);
if (resultado > 0)
{
MessageBox.Show("Persona Guardado Con Exito!!", "Guardado", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("No se pudo guardar el PERSONA", "Fallo!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

richTextBox1.Clear();
richTextBox1.Text = ";RUT =" + System.Environment.NewLine + ";FECHA_NACIMIENTO =" + System.Environment.NewLine + ";SEXO =" + System.Environment.NewLine + ";PROFESION =" + System.Environment.NewLine + ";PAIS = Chile" + System.Environment.NewLine + ";REGION =" + System.Environment.NewLine + ";CIUDAD =" + System.Environment.NewLine + ";COMUNA =" + System.Environment.NewLine + ";DOMICILIO =" + System.Environment.NewLine + ";FONO1 =" + System.Environment.NewLine + ";FONO2 =" + System.Environment.NewLine + ";E_MAIL =" + System.Environment.NewLine + ";RELACION =" + System.Environment.NewLine + ";EMPRESA = " + System.Environment.NewLine + ";COMENTARIO =" + System.Environment.NewLine;
textBox2.Clear();
}
}

private void Form1_Load(object sender, EventArgs e)
{
IOBase.ObtenerConexion();
label1.Text = "Conectado...";

comboBox1.SelectedText = "CIUDAD";

richTextBox1.Clear();
richTextBox1.Text = ";RUT =" + System.Environment.NewLine + ";FECHA_NACIMIENTO =" + System.Environment.NewLine + ";SEXO =" + System.Environment.NewLine + ";PROFESION =" + System.Environment.NewLine + ";PAIS = Chile" + System.Environment.NewLine + ";REGION =" + System.Environment.NewLine + ";CIUDAD =" + System.Environment.NewLine + ";COMUNA =" + System.Environment.NewLine + ";DOMICILIO =" + System.Environment.NewLine + ";FONO1 =" + System.Environment.NewLine + ";FONO2 =" + System.Environment.NewLine + ";E_MAIL =" + System.Environment.NewLine + ";RELACION =" + System.Environment.NewLine + ";EMPRESA = " + System.Environment.NewLine + ";COMENTARIO =" + System.Environment.NewLine;
}

private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}

private void button3_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = PersonasDAL.Buscar(textBox2.Text);
}

Persona xname { get; set; }

private void button4_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
xname = PersonasDAL.ObtenerPersona(id);
textBox1.Text = Convert.ToString(id);
textBox2.Text = xname.Nombre;
richTextBox1.Text = xname.Info;
//MessageBox.Show(ClienteSeleccionado.Id);
//MessageBox.Show(ClienteSeleccionado.Nombre);
//this.Close();
}
else
MessageBox.Show("debe de seleccionar una fila");





}

private void button5_Click(object sender, EventArgs e)
{

if (textBox1.Text=="")
{
MessageBox.Show("NO puede ACTUALIZAR si no ha agregado a BD antes", "Puede AGREGAR o LIMPIAR Todo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
Persona pPersona = new Persona();

pPersona.Nombre = textBox2.Text.ToString();
pPersona.Info = richTextBox1.Text.ToString();
pPersona.Id = Convert.ToInt32(textBox1.Text.ToString());

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

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}

string Item { get; set; }

private void button6_Click(object sender, EventArgs e)
{
if (textBox3.Text == "")
{
MessageBox.Show("NO puede BUSCAR si no ha agregado String!", "Puede Agregar string o LIMPIAR Todo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
string texto = "";
texto = comboBox1.Text.ToString();
Item = comboBox1.Text.ToString();
dataGridView1.DataSource = PersonasDAL.BuscarFULL(Item, textBox3.Text);
}
}



private void button8_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
richTextBox1.Text = ";RUT =" + System.Environment.NewLine + ";FECHA_NACIMIENTO =" + System.Environment.NewLine + ";SEXO =" + System.Environment.NewLine + ";PROFESION =" + System.Environment.NewLine + ";PAIS = Chile" + System.Environment.NewLine + ";REGION =" + System.Environment.NewLine + ";CIUDAD =" + System.Environment.NewLine + ";COMUNA =" + System.Environment.NewLine + ";DOMICILIO =" + System.Environment.NewLine + ";FONO1 =" + System.Environment.NewLine + ";FONO2 =" + System.Environment.NewLine + ";E_MAIL =" + System.Environment.NewLine + ";RELACION =" + System.Environment.NewLine + ";EMPRESA = " + System.Environment.NewLine + ";COMENTARIO =" + System.Environment.NewLine;
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
dataGridView1.ClearSelection() ;

}

private void button7_Click_1(object sender, EventArgs e)
{

if (textBox1.Text == "")
{
MessageBox.Show("No puede ELIMINAR si no ha agregado a BD antes", "Puede AGREGAR o LIMPIAR Todo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{

if (MessageBox.Show("Esta Seguro que desea eliminar PERSONA Actual", "Estas Seguro??", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
if (PersonasDAL.Eliminar(Convert.ToInt32(textBox1.Text.Trim())) > 0)
{
MessageBox.Show("PERSONA Eliminado Correctamente!", "PERSONA Eliminado", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("No se pudo eliminar el PERSONA", "PERSONA No Eliminado", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
else
{
MessageBox.Show("Se cancelo la eliminacion", "Eliminacion Cancelada", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}



}
}
}



=================================
IOBase.cs
-------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace Agenda
{
class IOBase
{
public static MySqlConnection ObtenerConexion()
{
MySqlConnection conectar = new MySqlConnection("server=127.0.0.1; database=agenda; Uid=root; pwd=;");
conectar.Open();
return conectar;
}

}
}
=======================================
PersonasDAL.cs
---------------
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace Agenda
{
class PersonasDAL
{

public static int Agregar(Persona pPersona)
{
int retorno = 0;
MySqlCommand comando = new MySqlCommand(string.Format("Insert into personas (Nombre,Info) values ('{0}','{1}')",pPersona.Nombre,pPersona.Info),IOBase.ObtenerConexion());
retorno = comando.ExecuteNonQuery();
return retorno;
}


public static List<persona> Buscar(string pNombre)
{
List<persona> _lista = new List<persona>();
MySqlCommand _comando = new MySqlCommand(String.Format(
"SELECT Id,Nombre,Info FROM personas where Nombre like '%{0}%'", pNombre), IOBase.ObtenerConexion());
MySqlDataReader _reader = _comando.ExecuteReader();
while (_reader.Read())
{
Persona pPersona = new Persona();
pPersona.Id = _reader.GetInt32(0);
pPersona.Nombre = _reader.GetString(1);
pPersona.Info = _reader.GetString(2);
_lista.Add(pPersona);
}
return _lista;
}





public static Persona ObtenerPersona(int pId)
{
Persona pPersona = new Persona();
MySqlConnection conexion = IOBase.ObtenerConexion();
MySqlCommand _comando = new MySqlCommand(String.Format("SELECT Id,Nombre,Info FROM personas where Id={0}", pId), conexion);
MySqlDataReader _reader = _comando.ExecuteReader();
while (_reader.Read())
{
pPersona.Id = _reader.GetInt32(0);
pPersona.Nombre = _reader.GetString(1);
pPersona.Info = _reader.GetString(2);
}
conexion.Close();
return pPersona;
}




//actualizar Persona
public static int Actualizar(Persona pPersona)
{
int retorno = 0;
MySqlConnection conexion = IOBase.ObtenerConexion();
MySqlCommand comando = new MySqlCommand(string.Format("Update personas set Nombre='{0}', Info='{1}' where id={2}", pPersona.Nombre, pPersona.Info, pPersona.Id), conexion);
retorno = comando.ExecuteNonQuery();
conexion.Close();
return retorno;
}



public static List<persona> BuscarFULL(string Item, string pNombre)
{
List<persona> _lista = new List<persona>();
MySqlCommand _comando = new MySqlCommand(String.Format(
"SELECT Id,Nombre,Info FROM personas"), IOBase.ObtenerConexion());
MySqlDataReader _reader = _comando.ExecuteReader();

char[] delimiterChars = { ';' };
string text = "";

while (_reader.Read())
{
Persona pPersona = new Persona();
pPersona.Id = _reader.GetInt32(0);
pPersona.Nombre = _reader.GetString(1);
pPersona.Info = _reader.GetString(2);
//AQUI DEBO PREGUNTAR POR LA INFO

text = pPersona.Info.ToString().ToUpper();

string[] words = text.Split(delimiterChars);

foreach (string s in words)
{
text = s.ToUpper();

if (text.StartsWith(Item.ToString().ToUpper()))
{
if (text.Contains(pNombre.ToString().ToUpper()))
{
_lista.Add(pPersona);
}
}

}
//----

}
return _lista;
}



public static int Eliminar(int pId)
{
int retorno = 0;
MySqlConnection conexion = IOBase.ObtenerConexion();
MySqlCommand comando = new MySqlCommand(string.Format("Delete From personas where Id={0}", pId), conexion);
retorno = comando.ExecuteNonQuery();
conexion.Close();
return retorno;
}


}
}



===============================================================
Persona.cs
---------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Agenda
{
class Persona
{
public int Id { get; set; }
public string Nombre { get; set; }
public string Info { get; set; }

public Persona() { }

public Persona(int pId, string pNombre, string pInfo)

{
this.Id = pId;
this.Nombre = pNombre;
this.Info = pInfo;
}

}
}


=======================================================
CREACION DE TABLA personas EN BASE DE DATOS 'agenda':
======================================================

-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 18-06-2016 a las 19:02:39
-- Versión del servidor: 10.1.10-MariaDB
-- Versión de PHP: 5.6.19

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de datos: `agenda`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `personas`
--

CREATE TABLE `personas` (
`Id` int(6) NOT NULL,
`Nombre` varchar(100) NOT NULL,
`Info` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `personas`
--




=====================================================
COMENTARIO PERSONAL
mi primer poyecto que funciono ... soy un aprendiz,
pero espero progresar en esto , OJO: solo me falto sacar
los acentos en las comparaciones .. ojala sirva este
ejemplo que me lelvo varias horas ..., saludos
a todos ...
Manuel Fuentes Briones (Chile)
contacto56@yahoo.es
==========================================
Questiongot some error on the search button Pin
Member 1067964413-Apr-16 22:05
Member 1067964413-Apr-16 22:05 
AnswerRe: got some error on the search button Pin
Member 1067964413-Apr-16 22:06
Member 1067964413-Apr-16 22:06 
QuestionParameterised Queries Pin
paul@paulharding.net4-Mar-16 5:05
paul@paulharding.net4-Mar-16 5:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.