RSS

Connect MySQL in Visual C#

22 Sep

Instructions:

  1. Download and Install MySQL Connection Driver in http://dev.mysql.com/downloads/connector/net/6.0.html
  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;” +
“PASSWORD=testpassword;”;
//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
cnMySQL.Open();
//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() + “,”;
listBox1.Items.Add(thisrow);
}
cnMySQL.Close();
}
Advertisements
 
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:

WordPress.com Logo

You are commenting using your WordPress.com 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: