Connect MySQL in Visual C#


  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() + “,”;