2012年6月25日 星期一

[C#] Connect to MySQL

First, download MySQL Connector/Net: http://dev.mysql.com/downloads/connector/net/ (2012-06-26). Then install it.

To connect to MySQL, add MySql.Data.dll to reference in your C# project. Then try the following sample snippet. Enjoy!

using MySql.Data.MySqlClient;

String connString = "server=<IP>;uid=<USERNAME>;pwd=<PASSWORD>;database=<DATABASE>";
MySqlConnection conn = new MySqlConnection(connString);

// Try to connection MySQL
try
{
    conn.Open();
}
catch (MySqlException e)
{
    // Do exception handling
}

// ...

// Do SQL command
string SQL_SelectFromYourTable = "select * from YourTable";
try
{
    MySqlCommand cmd = new MySqlCommand(SQL_SelectFromYourTable, conn);
    MySqlDataReader reader = cmd.ExecuteReader();

    if (!reader.HasRows)
    {
        // Do something with your empty table
    }
    else
    {
        while (reader.Read())
        {
            // Do something with each record
        }
        reader.Close();
    }
}
catch (MySqlException e)
{
    // Do exception handling
} 
      

沒有留言:

張貼留言