Connect MySQL in Visual C#

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();
}