Forgot Password / Register
Site Statistics
Total Members: 520
Total Tutorials: 242
Newsest User: 8884244477
Todays Unique Hits: 507
0 Users 2 Guests Online

Connect to a MySQL Server

This tutorial will show you how to get a basic MySQL Connection going in C# Express 2008.

You will first want to get the MySQL Connector from their website at This Link

Select a mirror close to you then download a Windows Binary ZIP File. Unpack the zip file and run the installer.
NOTE: If you have an earlier version of 5.2 you MUST uninstall it in order to install this new one.

After it is installed you can start Visual C# and create a new Windows Forms project.

TutorialNinja Image

After the new project is created you will want to go to your solution explorer and right click on the project name and click "Add Reference"

TutorialNinja Image

After you do that go to the Browse tab and open
C:\Program Files\MySQL\MySQL Connector Net 5.2.5\Binaries\.NET 2.0

Click the MySql.Data.dll and hit enter thus adding it to your new project.

After it has been added you can double click your form and where it has

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

Add After
using MySql.Data.MySqlClient;

Lets not have the program connect directly... Instead, lets place in our user details :D

Create 3 labels,
3 textboxes
and 1 button.

Here is the information as follows.

Label 1
Name: lblHost
Text: MySQL Host

Label 2
Name: lblUser
Text: MySQL User

Label 3
Name: lblPass
Text: MySQL Pass

Textbox 1
Name: txtHost

Textbox 2
Name: txtUser

Textbox 3
Name: txtPass
PasswordChar: *

Button 1
Name: cmdTestConnection
Text: Test Connection

This here is my outcome ;)
TutorialNinja Image

Your form design is done! Now onto the raw code.

Double click your Test Connection button and under

public frmMain()

Hit enter one more time and place the following lines of code.
private String Host;
private String User;
private String Pass;

TutorialNinja Image

Go back into your void of pressing the button and add the following:
this.Host = txtHost.Text;
this.User = txtUser.Text;
this.Pass = txtPass.Text;
MySqlConnection MyCon = new MySqlConnection("server=" + this.Host + "; user id=" + this.User + "; password=" + this.Pass + "; pooling=false;");
MessageBox.Show("MySQL Connection Succeeded", "Success");
catch (MySqlException ex)
MessageBox.Show("MySQL Connection Failed! " + ex.Message, "Error");

After that you can press F5 too see it in action. Fill out the fields and press "Test Connection" and you should get something like the following:

TutorialNinja Image

And that concludes this tutorial! Stick around and my next one will add onto this one and allow you to connect to a database and select things from tables ;)
Posted on Monday 19th January 2009 at 12:11 AM
Nice tutorial