Connect MySQL in Visual C#

22 Sep


  1. Download and Install MySQL Connection Driver in
  2. Create a test project in Visual C#
  3. Add Reference to MySQL.Data
  4. Add “using MySql.Data.MySqlClient;”

using MySql.Data.MySqlClient;

private void connectoToMySql(string server)
//set your connection string.
//NOTE: I am a big supporter of having the connection
//stored in the web.config, not inline like this
string connString = “SERVER=” + server + “;” +
“DATABASE=mydatabase;” +
“UID=testuser;” +
//create your mySQL connection
MySqlConnection cnMySQL = new MySqlConnection(connString);
//create your mySql command object
MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
//create your mySQL reeader object
MySqlDataReader reader;
//set the command text (query) of the
//mySQL command object
cmdMySQL.CommandText = “select * from mycustomers”;
//open the mySQL connection
//execute the reader, thus retrieving the data
reader = cmdMySQL.ExecuteReader();
//while theres data keep reading
while (reader.Read())
string thisrow = “”;
for (int i= 0;i<reader.FieldCount;i++)
thisrow+=reader.GetValue(i).ToString() + “,”;
Leave a comment

Posted by on September 22, 2009 in C#


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: