Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

Connect WPF with Wamp Server MySql

5.00/5 (2 votes)
5 Aug 2014CPOL 18K  
The easy way to connect to Mysql using Wamp server on WPF

Introduction

We always need to use database in our project, in WPF we usually use SQLITE, but what if we want to deploy our database? Then you can now work with WampServer and it is so easy to do that.

Using the Code

First of all, you create a new database in the WampServer using PhpMyAdmin, then create tables.

To connect with this database, you must add the Reference <a href="http://www.dllme.com/dll/download/13622/MySql.Data.DLL">MySqlData</a>, you can find it when you download this sample.

For the local connection, the server must be localhost, if you don't set a password, then it is Empty by default and enter the name of your database that you created.

Add this following code:

C#
MySql.Data.MySqlClient.MySqlConnection conn;
private void ConnectDatabase()
{
    string cn = "server=localhost; user id=root; password=''; database=cabinet";
    conn = new MySql.Data.MySqlClient.MySqlConnection(cn);
    conn.Open();
}

After successful Connection, you can now retrieve or add some information on the database.

Here is an example of how to read data:

C#
string mySelectQuery = "SELECT * FROM Patient";
MySqlCommand filmsCommand = new MySqlCommand(mySelectQuery, conn);

MySqlDataReader reader = filmsCommand.ExecuteReader();

while (reader.Read())
{
      int  Numero = reader.GetInt16("Num");
       string name = reader.GetString("Nom");
}

filmsCommand.Connection.Close();

PS: You must always close the SqlCommand after any Transaction.

If you now want to update your data, then insert the following code:

C#
string mySelectQuery = "INSERT INTO Patient ( Nom , Prenom , Adresse , Telephone ,
Date_Naissance , Date_Ouverte) VALUES ('Bouhlel', 'BHL', 'Sfax','22108069','29/08/1991','" +
DateTime.Now.Date.ToShortDateString() + "')";

MySqlCommand filmsCommand = new MySqlCommand(mySelectQuery, conn);

filmsCommand.ExecuteNonQuery();
filmsCommand.Connection.Close();

History

Connecting to database has become the easiest thing that we can do now, though we still face problems when it comes to executing the transactions.

License

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