воскресенье, 5 сентября 2010 г.

How to connect to MySQL via C# .Net and the MySql Connector/Net



This article and tutorial describes and demonstrates how you can connect to MySQL in a c# application.
  • First, you need to install the mysql connector/net, it is located at: http://dev.mysql.com/downloads/connector/net/
  • Next create a new project
  • Next add reference to: MySql.Data
  • Next add "using MySql.Data.MySqlClient;"
  • Finally add the following code to your application:


private void button1_Click(object sender, System.EventArgs e)
  {
   string MyConString = "SERVER=localhost;" +
    "DATABASE=mydatabase;" +
    "UID=testuser;" +
    "PASSWORD=testpassword;";
   MySqlConnection connection = new MySqlConnection(MyConString);
   MySqlCommand command = connection.CreateCommand();
   MySqlDataReader Reader;
   command.CommandText = "select * from mycustomers";
   connection.Open();
   Reader = command.ExecuteReader();
   while (Reader.Read())
   {
    string thisrow = "";
    for (int i= 0;i
      thisrow+=Reader.GetValue(i).ToString() + ",";
    listBox1.Items.Add(thisrow);
   }
   connection.Close();
  }

Комментариев нет: