ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

How to Connect MySQL Database to C#.net

In this tutorial, I will teach you how to connect MySQL Database to C#.net using Microsoft Visual Studio 2008. With this, you can establish a connection between MySQL Database and C#.net.

 

Let’s begin:

 

1. Create a database in the MySQL and name it “dbconnect

2. Open Microsoft Visual Studio and create a new windows form application for C#. Then, drag a button and do the form just like this.

ConnectionMySQLCsharp.fig.1

3. Double-click a button to fire the click event handler of it.

4. After that, do the following codes to established a connection between MySQL Database and C#.net in the method.

Note: Add “MySQL.Data.dll” as your refernce and put “using MySql.Data.MySqlClient; above the namespace to access MySQL library.

//initialize sql connection
 MySqlConnection con = new MySqlConnection();
 //set a connection string
 con.ConnectionString = "server=localhost;user id=root;password=;Database=dbconnect;";
 //opening connection
 con.Open();
 //validating connection

 if (con.State == ConnectionState.Open)
 {
 if (button1.Text == "Connect Me")
 {
 button1.Text = "Disconnect Me";
 this.Text = "Connected";
 }
 else
 {
 button1.Text = "Connect Me";
 this.Text = "Disconnected";
 con.Close();
 }

 }

5. Press F5 on the keyboard to run your project.

Output:

ConnectionMySQLCsharp.fig.2

This is a simple yet powerful method to do because without this, you can’t proceed to the process of CRUD.

 

Download Source Code

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!