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

Code:
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();
da_my1.Fill(dt_my1);

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

con_my.Open();
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
con_my.Close();

So add the MySQL database and enjoy...

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews