Friday, April 8, 2011

Mysql Connect in C#

To connect mysql in C# you have to download a .dll file from mysql website.
This file you can not find directly, but you will find a setup file from web.
But from this web link you can download directly this file.
C# mysql connector(unavailable)
You can add this file into the reference folder from your project or
Copy this into your Current directory.
Name of the file is MySql.Data.dll.
Sample code for C# and mysql:

  string host = "localhost";
            string database = "databasename";
            string user = "root";
            string password = "";
            string strSQL = "SELECT * FROM table";

            string strProvider = "Data Source=" + host + ";Database=" + database + ";User ID=" + user + ";Password=" + password;
            try
            {
                MySqlConnection mysqlCon = new MySqlConnection(strProvider);
                mysqlCon.Open();

                if (mysqlCon.State.ToString() == "Open")
                {
                   // Console.WriteLine("Database Connection Open");
                   // Console.WriteLine("------------------------");

                    MySqlCommand mysqlCmd = new MySqlCommand(strSQL, mysqlCon);
                    MySqlDataReader mysqlReader = mysqlCmd.ExecuteReader();

                   // Console.WriteLine("Id\tName\tLastName");
                  //  Console.WriteLine("------------------------");

                    while (mysqlReader.Read())
                    {
                        String str = mysqlReader.GetValue(0).ToString();
                        MessageBox.Show(str);
                    }

                }

                mysqlCon.Close();

            }
            catch (Exception er)
            {
             //   Console.WriteLine("An Error Occured" + er.Message);
            }

This code will connect mysql in C# and retrieve data.
Thank You.

No comments:

Post a Comment