Thursday, July 10, 2014

Add MySQL Database with .NET Application in C#

In this article I will show you how to add a MySQL database with your .NET application in C#.

For this you need to add MySql.Data.dll as a reference in your project. You can download the dll from here. After downloading the dll select your project and right click on the project, click on the add reference menu. Then browse the dll to add it.

After adding add a new namespace in your .cs page.

using MySql.Data.MySqlClient;

Now after this create a new string which will act as your connection string.

string MySqlConn = "Server=<Ip address>;Port=<Port no>;
                  Database=<Database name>;Uid=<Username>;Pwd=<Password>;";

Generally use port no 3306 as port no in your connection string.

Now to create a new connection

MySqlConnection con_my = new MySqlConnection(MySqlConn);

Now for command write the follow code

MySqlCommand cmd_my;            
cmd_my = con_my.CreateCommand();
cmd_my.CommandText = "Select * from <table name>";

Now to get the value into a datatable add these.

MySqlDataAdapter da_my1 = new MySqlDataAdapter(cmd_my);
DataTable dt_my1 = new System.DataDataTable();

If you want to perform any insert, update, delete query then these are the code to proceed.

MySqlCommand cmd_my1;
cmd_my1 = con_my.CreateCommand();
cmd_my1.CommandText = "INSERT INTO <tblname>(col1,clo2,col3) 
                VALUES('" + data1 + "','" + datat2 + "','" + data3) + "')";
cmd_my1.ExecuteNonQuery();  // Returns no of row(s)affected

So add the MySQL database and enjoy...


Post a Comment

Popular Posts