Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Connect to MySQL using C# and Connector/Net

This tutorial explains how to connect to a MySQL database using the Connector/Net ADO.NET driver.

On Saturday, September 29th 2007 at 07:53 AM
By Syed Hussain (View Profile)
*****   (Rated 4.5 with 35 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

In this mini tutorial I will teach you how to get connected to a MySQL database. This is really quite simple. All you need to do is download Connector/Net which is a fully-managed ADO.NET driver written in 100% pure C#. Download the installer and install Connector/Net. After installation load your C# IDE. Begin a new console project.

The first thing you need to do is add a reference to your project. Open the “Add Reference” dialog box. Under the .Net tab scroll down to MySQL.Data and add this reference to your project. Before we start with the actual code we need to add two namespaces. Add the following namespaces.

using MySql.Data.MySqlClient;
using MySql.Data.Types;

Finally it’s now time to write some code. When connecting to any database you usually need to set up a provider. This provder is of type string and simply consists of information such as database to connect to, username, password and url/name of the machine in which the database is hosted. This provider sring is different for different databases. The provider string needed to connect to a MySQL database is listed below.

string strProvider = "Data Source=" + host + ";Database=" + database + ";User ID=" + user + ";Password=" + password;

In the provider string above we simply supply the data source, which is the url/ip/name of the computer which the database is hosted on. We also supply the database name to connected to and the username and password.

If your using a default MySQL installation, the username should be “root” and the password should be the password you used in the installation process.

After setting up a provider, you need to create a connection to the database. You do this by using the MySqlConnection object.

When creating an instance of MySqlConnection, you supply the provider in it’s constructor.

MySqlConnection mysqlCon = new MySqlConnection(strProvider);

We then use the Open() method of mysqlCon object to open a connection to the database.

MySqlConnection mysqlCon = new MySqlConnection(strProvider);
mysqlCon.Open();

Now that the connection is open, you need to query the database. You need to send an SQL statement to get the results from the database. This is done using the MySqlCommand object. In the constructor of the MySqlCommand you supply an SQL statement and also the connection object.

string strSQL = "SELECT * FROM [Your Table Here]";
MySqlCommand mysqlCmd = new MySqlCommand(strSQL,mysqlCon);

So now you can send an SQL statement to the database. But you need a way to store the records, for this you use the MySqlDataReader object.

MySqlDataReader mysqlReader = mysqlCmd.ExecuteReader();

Now the MySqlDataReader object will contain all the records from the database. The MySqlDataReader object is a read only onject, which allows you to quickly get records out of a database table. It can not be used to update a database table.

To get records from the MySqlDataReader object you use a while loop. The loop uses the MySqlDataReader objects Read() method, to get the data for each row.

while (mysqlReader.Read())
{

Console.WriteLine(mysqlReader.GetInt32(0) + "\t" + mysqlReader.GetString(1) + "\t" + mysqlReader.GetString(2));
}

Finally you use the appropriate methods of the MySqlDataReader object to get the data from each column. For example the first column is returned as an Integer using the GetInt32() method, while the second and third columns return string data.

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Deepa on Thursday, October 25th 2007 at 02:30 AM

hi
your exampe coding gave me some idea but i m not able to implement
can u help me out in adding just the user name and pwd to the database using mysql in asp.net.
Hepl me out

by HondaCop on Wednesday, January 2nd 2008 at 03:11 PM

WHAT A LIFE SAVER!!! Thanks so much for this AWESOME code. Can I simply include the MySql.Data.dll fiel with my application and it will work on my user\'s computers? Or does each person need to have the Connector installed on their machine?

by SomeOne on Wednesday, March 12th 2008 at 01:47 AM

No they don't need the Net/Connector installed on their computer, just the MySql.Data.dll.
Awesome tut!

by Trd on Monday, March 24th 2008 at 03:20 PM

WOW! You're the best!!!

Thank you very much.

by Nisar on Wednesday, April 2nd 2008 at 11:24 PM

It works great but only with localhost and generates error {Un able to connect any of Mysql Host}if Mysql database is hosted on remote server.Kindly explain breifly that what settings to make from server side to get connect with server remotely if we have Mysql 3.23.58 on server and how to give access to Mysql

by swadata on Friday, May 16th 2008 at 06:09 AM

Thankyou! Thankyou! Thankyou!

by Imran on Tuesday, July 29th 2008 at 08:01 AM

Very Good ,Thank you ,

by Art on Tuesday, July 29th 2008 at 10:49 PM

Syed,

Great writeup- short and to the point. Perfect, thanks.

by naren on Thursday, August 14th 2008 at 07:26 AM

Exactly ... short and to the point...All that u need ... other sites confuse u ..

Thanks Syed ..

by Json on Friday, August 29th 2008 at 06:26 PM

Thanks, this article helped me understand a bit more clear than the docs did. I furthered the code and created a 'fetchAll' function which will return all data from a table or based on a where clause. It then does type checking and stores the field names and values in an array.

by shentho on Wednesday, September 24th 2008 at 08:27 AM

Great tutorial!

by umesh on Friday, November 28th 2008 at 12:52 AM

I am not able to add the MySql.Data.Dll and for this reason the name space
using MySql.Data.MySqlClient;
is throwing exceptin.
Please Help me.

by Sujayath on Tuesday, December 16th 2008 at 12:20 AM

I want to display all record in the databse field when i m using while(dr.read()) it cannot execute it on textbox box..coding below

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using MySql.Data.MySqlClient;
using System.Web.Mail;
//using System.Net.Mail;


public partial class _Default : System.Web.UI.Page
{
public conn c1 = new conn();
public MySql.Data.MySqlClient.MySqlCommand cmd;
public MySql.Data.MySqlClient.MySqlCommand cmd1;
public MySql.Data.MySqlClient.MySqlDataReader dr;
public MySql.Data.MySqlClient.MySqlDataAdapter da;
public MySql.Data.MySqlClient.MySqlDataAdapter da1;
public string q, q1, q2, cid;
protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{

etview();

}
}
public void etview()
{

bool co = c1.oc();
if (!co)
{
}
else
{

q1 = "select Email_Id from customer_details ";
cmd = new MySqlCommand(q1, c1.con);
dr = cmd.ExecuteReader(CommandBehavior.Default);

while(dr.Read())
{
//while (reader.Read())
//{ // Read the value...
// string sap = reader.GetValue(27).ToString();
//txtto.Text = sap;
//}
txtto.Text = dr["Email_Id"].ToString();
txtto.Text = txtto.Text ",";

}

}
//dr.Close();
c1.cc();
}

by hikizume976 on Friday, January 2nd 2009 at 08:45 AM

I've spent almost half an hour looking for something to help me with this. I was looking for a way to connect to my mysql database using C#. I needed to start from scratch.

Everything I needed to know I was able to find right here.

thank you for putting together a simple yet effective guide.

by bina on Sunday, February 1st 2009 at 11:47 PM

Worked like a charm. Thanks!

by Ola on Monday, February 9th 2009 at 01:44 PM

Can this work with Windows Application??

by Bob on Wednesday, April 1st 2009 at 02:52 AM

Don't forget to close your connections when you have finished with them!!

[code]
mysqlReader.Close();
mysqlCon.Close();
[/code]

by y sophany on Thursday, April 2nd 2009 at 04:15 AM

it's hard to understand

by y sophany on Thursday, April 2nd 2009 at 04:15 AM

it's hard to understand

by y sophany on Thursday, April 2nd 2009 at 04:15 AM

it's hard to understand

by mukta on Wednesday, June 3rd 2009 at 02:56 AM

when i go to install the mysql-connector-net-1.0.10.1.exe it shows that "setup is required for .net framework 1.1" But my .net framework version is 3.5 ...how can i solve this problem?
where i can get mysql.Data.dll file ?

by jaikit on Wednesday, June 10th 2009 at 04:30 PM

thank you...:)

by jaikit on Wednesday, June 10th 2009 at 04:49 PM

thank you...:)

by trd on Saturday, June 20th 2009 at 08:56 AM

mukta, go and download a newer version of mysql-connector.

by tsiry on Friday, July 10th 2009 at 12:59 AM

hi! Great tutorial!
please can you tell me how to connect C# mysql with a server not a locahost but on server like 192.168.0.2?

by j on Wednesday, July 29th 2009 at 12:59 PM

thanks alot,
short and to the point

by Zahid on Wednesday, August 12th 2009 at 05:28 AM

http://dev.mysql.com/doc/refman/6.0/en/connector-net-visual-studio-making-a-connection.html

Detail Tutorial

by Ant on Monday, September 28th 2009 at 03:50 PM

I had to add my PC address to Remove SQL in cpanel on my server and then it just worked. It's not often that a tutorial works so easily. Thank you.

by Ant on Monday, September 28th 2009 at 03:50 PM

I had to add my PC address to Remove SQL in cpanel on my server and then it just worked. It's not often that a tutorial works so easily. Thank you.

by Bryan Karlsson on Friday, November 6th 2009 at 04:53 AM

Isn't the MySql.Data.Reader an class? The author of this minitutorial must learn to separate different terms.

by soldio on Wednesday, February 3rd 2010 at 02:52 AM

Great tutorial... Very informative.. Thanks for sharing.. 'twas a life saver.. I needed this for school..

I just have one question... Which is better to use? this one? or odbc connector? please reply.. Thanks..

by savita on Wednesday, March 10th 2010 at 01:07 AM

nice tutorial

by santlal on Tuesday, March 30th 2010 at 12:23 AM

How to execute dos command in ASP.NET.

by arifur rahman on Thursday, May 20th 2010 at 01:01 PM

you can see this tutorial for more details.http://learneveryday.net/asp-net/mysql/insert-in-to-mysql-with-asp-net-part-1/

by Krishanu Mukherjee on Wednesday, June 9th 2010 at 06:02 AM

Thanks dude!!
I am very much thankfull to u,becoz i am trying to connect c# with Mysql from last 4 hrs.but after so many search,i came to these site and after that followed ur steps.
Thanks once again
If u need any help frm me,just let me knw.I will be happy if i can help u.

by KRUNAL on Saturday, June 26th 2010 at 02:11 PM

hi,
can u help me out in adding just the user name and pwd to the database using mysql in c#.net
Help me out.

by xuser on Saturday, July 24th 2010 at 07:07 PM

for inserting values in the database we need only to query like:
string strSQL = "INSERT INTO [Your Table Here] VALUES .... ";
MySqlCommand mysqlCmd = new MySqlCommand(strSQL,mysqlCon);

or i will need another object, something like " MySqlDataWriter"

???


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources