How to Access MySQL with C#

Using a MySQL Database with a C# Windows Application

© Mark Alexander Bain

May 5, 2009
MySQL and C#, MySQL
C# and MySQL make a very powerful combination, and it's all made possible by using the MySQL .NET connector

Many C# applications use a database for the storage of any information that they need, and one of the most commonly used databases is MySQL. That's not only because of MySQL's reliability but it's also because the contents of a MySQL database can be easily accessed and manipulated from C#.

That is, of course, if the C# programmer is using the MySQL .Net Connector.

Obtaining the MySQL .Net Connector

The first step to using the MySQL .Net Connector is to download its installation program from the MySQL Connector/Net web page. Once the programmer has run the downloaded file then the connector will be available for any C# projects.

Preparing the MySQL Database

No additional work is required for a MySQL database to work with the MySQL .NET connector except, of course, for the database and its contents to be created. For example:

Create database aec;
Grant insert, update, select, delete on aec.* to 'aec_user'@'localhost' identified by 'aec';
Create table aec.samples (
id int auto_increment,
description varchar(255),
site_id int,
received datetime,
processed datetime,
primary key (id));
Insert into aec.samples (description, site_id, received) values ('clay desposit', 27, now());
Insert into aec.samples (description, site_id, received) values ('burial urn', 103, now());

Now it's just a matter of accessing the MySQL database from a C# project.

Adding the MySQL Connector to the C# Project as a Reference

The MySQL .NET connector will not automatically be available to a new C# project. In order for that to happen the programmer must add it as a reference. How this happens will depend on the IDE (Integrated Design Environment) being used.

For example, in SharpDevelop the programmer needs to click on "Projects" and then "References". They will then be able to select "MySql.Data" from the list of available references. It can then be accessed from C# project's code.

Loading the MySQL Connector with C#

With the MySQL .NET connecter to be included in the C# project, the next step is to declare the reference as part of the code:

using MySql.Data.MySqlClient;

In this example a dataset is to be used. Therefore the System Data object must be accessed:

using System;
using System.Data;

As well as the normal objects required for the creation of a form:

using System.Windows.Forms;
using System.Drawing;

The project is now ready for the form itself to be created.

Using MySQL Data in a Windows Application Form

This application will:

  • create a connection to a MySQL database
  • run a SQL query and read the results using a MySQL data adaptor
  • load the results into a grid in a form

This is all done in by extending the default C# form class:

public class MainForm : Form {
private MySqlConnection connection = new MySqlConnection ();
private MySqlDataAdapter data = new MySqlDataAdapter ();
DataGrid gridInfo = new DataGrid();

The MySqlConnection object uses a connection string and the "open" method to make a connection to the MySQL database:

public static void Main () {
Application.Run(new MainForm ());
}
public MainForm() {
connection.ConnectionString =
"server=localhost;"
+ "database=aec;"
+ "uid=aec_user;"
+ "password=aec;";
connection.Open ();

Next the SQL query is created:

MySqlCommand command = connection.CreateCommand ();
command.CommandText = "select * from samples";

And then the results loaded into a data set (which, in this example, is given the name "sample_data"):

data.SelectCommand = command;
DataSet dataset = new DataSet();
data.Fill(dataset,"sample_data");

The grid can then be loaded with the contents of the data set:

gridInfo.DataSource = dataset;
gridInfo.DataMember = "sample_data";
gridInfo.Dock = DockStyle.Fill;

Finally the populated grid is added to the form:

this.Controls.Add (gridInfo);
}

If the form is compiled at this point then it will contain a grid containing the results of the MySQL query.

Closing the Connection

A MySQL connection ends by using the "close" method. Here the connection is closed when the form is unloaded:

~MainForm() {
connection.Close();
}

And with just those few lines of code the MySQL database can be accessed and read, with the result of a query being used in the C# application.


The copyright of the article How to Access MySQL with C# in Windows Programming is owned by Mark Alexander Bain. Permission to republish How to Access MySQL with C# in print or online must be granted by the author in writing.


MySQL and C#, MySQL
A C# Windows Application Accessing MySQL, Mark Alexander Bain
     


Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo