using mysql with asp_net sample code for handing database operations mysql asp_net

Using MYSQL with any .net languages is very easy. There is one component developed by MYSQL that offers seemless interaction between any .net language and mysql server.

All you need is to download mysql.data.dll from mysql website, which is known as mysql connector net.

Here is the sample code that fetches the datatable from the mysql database.

string ConnectionString = "your mysql connection string";
  
        public DataTable GetDataTable(string Query)
        {

            MySql.Data.MySqlClient.MySqlConnection SqlConn = new MySql.Data.MySqlClient.MySqlConnection(ConnectionString);
            MySql.Data.MySqlClient.MySqlCommand SqlCmd = new MySql.Data.MySqlClient.MySqlCommand(Query, SqlConn);
            MySql.Data.MySqlClient.MySqlDataAdapter SqlDataAdt = new MySql.Data.MySqlClient.MySqlDataAdapter();
            DataSet ResultSet = new DataSet();
            DataTable Result = new DataTable();
            try
            {
                SqlCmd.CommandType = CommandType.Text;
                SqlCmd.CommandTimeout = 30;

                SqlDataAdt.SelectCommand = SqlCmd;

                if (SqlConn.State == ConnectionState.Open)
                {
                    SqlDataAdt.Fill(ResultSet, "Result");
                    Result = ResultSet.Tables["Result"];
                }
                else if (SqlConn.State == ConnectionState.Closed)
                {
                    SqlConn.Open();
                    SqlDataAdt.Fill(ResultSet, "Result");
                    Result = ResultSet.Tables["Result"];
                }
                else
                {
                    SqlConn.Close();
                    SqlConn.Open();
                    SqlDataAdt.Fill(ResultSet, "Result");
                    Result = ResultSet.Tables["Result"];
                }
                return Result;
            }
            catch (Exception ex)
            {
                Result.Dispose();
                ResultSet.Dispose();
                SqlDataAdt.Dispose();
                SqlCmd.Dispose();
                SqlConn.Close();
                return null;
            }
            finally
            {
                Result.Dispose();
                ResultSet.Dispose();
                SqlDataAdt.Dispose();
                SqlCmd.Dispose();
                SqlConn.Close();
            }
        }

 Make sure that the dll file MySQL.Data.dll is visible to your application in which you want to use the mysql database.

 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading








Quality & Affordable Web Development | About the Author | Hosted By Windows Hosting | Discuss With Experts At Webmaster Forums