ARTICLE

Connecting to MySQL Using C#.NET

Posted by Ravindra T C Articles | Visual C# July 16, 2012
This article shows you how to connect to a MySQL database using the MySQL Connector for .NET. I will also show you how to update MySQL database records using C#.
Reader Level:

Introduction

This article shows you how to connect to a MySQL database using the MySQL Connector for .NET. I will also show you how to update MySQL database records using C#.

The prerequisites for running the sample are:

  • Install Visual Studio 2008 or Visual Studio 2010
  • Install MySQL database on your local machine
  • Use the MySQL database admin tool that allows you to create databases and run SQL statements. I am using phpMyAdmin which is a web interface.
  • Download and install the MySQL Connector.

Getting Started

Run the XAMPP application; it will automatically install the Apache Server, MySQL database and FileZilla. After installation check whether these services are running or not. The following XAMPP control panel shows which of those services are currently running.

MySql1.jpg

Now the following steps will show how to connect to the MySQL database using C#.Net.

STEP 1:
 
Open the MySQL Admin page and create a new database:

MySql2.jpg

STEP 2:

After creating a new database, create a new table:

MySql2.5.jpg

STEP 3:

After creating the new table, open Visual Studio and click on the new project and give the project a name; it will open the new project, then click on the solution explorer (F4); right-click on "Reference" to add a new reference into the project. Add a reference for those two .dll files to the project (MySql.dll (Win apps), MySql.web.dll (Web apps)).

MySql3.jpg

STEP 4:

Add the namespace to the project:

MySql4.jpg

STEP 5:

Create a MySQL connection string:

MySql5.jpg

STEP 6:
 
The following code will insert the data into the MySQL table:

MySql6.jpg

STEP 7:

The following function will load the data from the table and bind it into the grid view:

MySql7.jpg

STEP 8:

The final result is as shown in the following form:

MySql8.jpg

Article Extensions
Contents added by ivan viera on May 16, 2013
COMMENT USING
Employers - Post Free Jobs