Click here to Skip to main content
15,885,216 members
Articles / Database Development / MySQL
Tip/Trick

How to Connect to MySQL Using C#

Rate me:
Please Sign up or sign in to vote.
4.85/5 (23 votes)
17 Jul 2012CPOL1 min read 539.9K   59   19
How to connect to a MySQL database using the MySQL Connector for .NET.

Introduction

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

Prerequisites

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

Getting Started

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

Image 1

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

Step 1

Open MySQL Admin page and create a new database.

Image 2

Step 2

After creating the new database, create a new table.

Image 3

Step 3

After creating the new table, open Visual Studio and click on New Project and name the project. It will open the new project, then click on Solution Explorer (F4), right click on “Reference” to add a new reference into the project. Reference those two .dll files to the project (MySql.dll (Win apps), MySql.web.dll (Web apps)).

Image 4

Step 4

Add namespace to the project.

Image 5Image 6

Step 5

Create a MySQL connection string.

Image 7

Step 6

The following code will insert the data into MySQL table.

Image 8

Step 7

The following function will load the data from the table and bind it into a GridView.

Image 9

Step 8

The final result is shown on the window form:

Image 10

License

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



Comments and Discussions

 
GeneralMy vote of 5 Pin
figgikim117-Sep-12 3:52
figgikim117-Sep-12 3:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.