In this article I will explain how to connect C# application with MySQL database
Introduction
In this article we will see how to display data in a Windows Forms application from a MySQL database table
Step 1:
Install MySQL database driver (MySQL Connector/NET) for .NET. Download it from this link http://dev.mysql.com/downloads/connector/net.
Step 2:
Create a new Windows Forms Application
Image may be NSFW.
Clik here to view.
Step 3:
Add reference to MySQL.Data.dll using Add Reference dialog box. Right click on References in the Solution Explorer to open Add Reference dialog box. Select MySQL.Data.dll from the .Net tab. You can also add it using Browse tab by select it from its installed path. In my machine it’s installed at C:\MySQL\MySQL Connector Net 6.1.2\Assemblies\MySQL.Data.dll.
Also, Add reference to System.Configuration assembly so that we can access our connection string from App.config file.
Step 4:
Add an Application Configuration File “App.config” and add connection string for connecting MySQL database. Write following inside <configuration> tag in App.config:
<connectionStrings> <add name="ConString" connectionString="server=localhost; database=databaseName; user id=youruserid; password=yourpassword;"/> </connectionStrings>
Step 5:
Drag a DataGridView and a Button control on Form1
Add following two namespace in the Form1.cs code view file:
using MySql.Data.MySqlClient; using System.Configuration;
Write following in the Button’s click event:
private void btnLoadData_Click(object sender, EventArgs e) { string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; MySqlConnection con = new MySqlConnection(ConString); string CmdString = "SELECT * FROM customers"; MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, con); DataSet ds = new DataSet(); sda.Fill(ds); dataGridView1.DataSource = ds.Tables[0].DefaultView; }
MySql.Data.MySqlClient namespace provides similar classes like we have in System.Data.SqlClient for connecting SQL Server. It is simply appended with “My” in MySQL like SqlConnection becomes MySqlConnection.
Output:
On clicking on the Button, data is displayed in the DataGridView from Customers table in MySQL database
Image may be NSFW.
Clik here to view.
Filed under: .Net, SQL, WinForm Image may be NSFW.
Clik here to view.
