程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> MySQL綜合教程 >> C#連接、訪問MySQL數據庫,

C#連接、訪問MySQL數據庫,

編輯:MySQL綜合教程

C#連接、訪問MySQL數據庫,


一、准備工具

visual stuido(本示例使用visual studio 2010)

MySql.Data.dll

mysql_installer_community_V5.6.21.1_setup.1415604646.msi(網上搜索去下載或者向我索要,聯系方式在http://xunwn.com/1010100)

二、新建DBUtility通用訪問MySQL類庫

1、在解決方案中新建一個DBUtility類庫,作為訪問MySQL的通用sql語句存放地點



2、引入MySql.Data.dll



3、配置web.config MySQL數據庫連接字符串

在解決方案根目錄下打開web.config配置文件,在connectionStrings節點中加入MySQL連接字符串

  <connectionStrings>
    <add name="DBConnectionString" connectionString="Data Source=127.0.0.1;Database=你的數據庫名;User ID=用戶名;Password=密碼" providerName="MySql.Data.MySqlClient"/>
  </connectionStrings>

4、新建SQLHelper通用MySQL訪問類,該類的定義如下:  

/// <summary>
    ///SQLHelper 的摘要說明
    /// </summary>
    public abstract class SQLHelper
    {
        //數據庫連接字符串(注意:這裡的“DBConnectionString”一定要與web.config文件中connectionStrings節點值一致)
        public static readonly string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();


        // 用於緩存參數的HASH表
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());


        /// <summary>
        ///  給定連接的數據庫用假設參數執行一個sql命令(不返回數據集)
        /// </summary>
        /// <param name="cmdType">命令類型(存儲過程, 文本, 等等)</param>
        /// <param name="cmdText">存儲過程名稱或者sql命令語句</param>
        /// <param name="commandParameters">執行命令所用參數的集合</param>
        /// <returns>執行命令所影響的行數</returns>
        public static int ExecuteNonQuery(string cmdText, CommandType cmdType = CommandType.Text, params MySqlParameter[] commandParameters)
        {


            MySqlCommand cmd = new MySqlCommand();


            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }


        /// <summary>
        /// 用執行的數據庫連接執行一個返回數據集的sql命令
        /// </summary>
        /// <remarks>
        /// 舉例:
        ///  MySqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="cmdType">命令類型(存儲過程, 文本, 等等)</param>
        /// <param name="cmdText">存儲過程名稱或者sql命令語句</param>
        /// <param name="commandParameters">執行命令所用參數的集合</param>
        /// <returns>包含結果的讀取器</returns>
        public static MySqlDataReader ExecuteReader(string cmdText, CommandType cmdType = CommandType.Text, params MySqlParameter[] commandParameters)
        {
            //創建一個MySqlCommand對象
            MySqlCommand cmd = new MySqlCommand();
            //創建一個MySqlConnection對象
            MySqlConnection conn = new MySqlConnection(connectionString);


            //在這裡我們用一個try/catch結構執行sql文本命令/存儲過程,因為如果這個方法產生一個異常我們要關閉連接,因為沒有讀取器存在,
            //因此commandBehaviour.CloseConnection 就不會執行
            try
            {
                //調用 PrepareCommand 方法,對 MySqlCommand 對象設置參數
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                //調用 MySqlCommand  的 ExecuteReader 方法
                MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                //清除參數
                cmd.Parameters.Clear();
                return reader;
            }
            catch
            {
                //關閉連接,拋出異常
                conn.Close();
                throw;
            }
        }


        /// <summary>
        /// 返回DataSet
        /// </summary>
        /// <param name="cmdType">命令類型(存儲過程, 文本, 等等)</param>
        /// <param name="cmdText">存儲過程名稱或者sql命令語句</param>
        /// <param name="commandParameters">執行命令所用參數的集合</param>
        /// <returns></returns>
        public static DataSet GetDataSet(string cmdText, CommandType cmdType = CommandType.Text, params MySqlParameter[] commandParameters)
        {
            //創建一個MySqlCommand對象
            MySqlCommand cmd = new MySqlCommand();
            //創建一個MySqlConnection對象
            MySqlConnection conn = new MySqlConnection(connectionString);


            //在這裡我們用一個try/catch結構執行sql文本命令/存儲過程,因為如果這個方法產生一個異常我們要關閉連接,因為沒有讀取器存在,


            try
            {
                //調用 PrepareCommand 方法,對 MySqlCommand 對象設置參數
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                //調用 MySqlCommand  的 ExecuteReader 方法
                MySqlDataAdapter adapter = new MySqlDataAdapter();
                adapter.SelectCommand = cmd;
                DataSet ds = new DataSet();


                adapter.Fill(ds);
                //清除參數
                cmd.Parameters.Clear();
                conn.Close();
                return ds;
            }
            catch (Exception e)
            {
                throw e;
            }
        }



        /// <summary>
        /// 用指定的數據庫連接字符串執行一個命令並返回一個數據集的第一列
        /// </summary>
        /// <remarks>
        ///例如:
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new MySqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="cmdType">命令類型(存儲過程, 文本, 等等)</param>
        /// <param name="cmdText">存儲過程名稱或者sql命令語句</param>
        /// <param name="commandParameters">執行命令所用參數的集合</param>
        /// <returns>用 Convert.To{Type}把類型轉換為想要的 </returns>
        public static object ExecuteScalar(string cmdText, CommandType cmdType = CommandType.Text, params MySqlParameter[] commandParameters)
        {
            MySqlCommand cmd = new MySqlCommand();


            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }


        /// <summary>
        /// 將參數集合添加到緩存
        /// </summary>
        /// <param name="cacheKey">添加到緩存的變量</param>
        /// <param name="commandParameters">一個將要添加到緩存的sql參數集合</param>
        public static void CacheParameters(string cacheKey, params MySqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }


        /// <summary>
        /// 找回緩存參數集合
        /// </summary>
        /// <param name="cacheKey">用於找回參數的關鍵字</param>
        /// <returns>緩存的參數集合</returns>
        public static MySqlParameter[] GetCachedParameters(string cacheKey)
        {
            MySqlParameter[] cachedParms = (MySqlParameter[])parmCache[cacheKey];


            if (cachedParms == null)
                return null;


            MySqlParameter[] clonedParms = new MySqlParameter[cachedParms.Length];


            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (MySqlParameter)((ICloneable)cachedParms[i]).Clone();


            return clonedParms;
        }


        /// <summary>
        /// 准備執行一個命令
        /// </summary>
        /// <param name="cmd">sql命令</param>
        /// <param name="conn">OleDb連接</param>
        /// <param name="trans">OleDb事務</param>
        /// <param name="cmdType">命令類型例如 存儲過程或者文本</param>
        /// <param name="cmdText">命令文本,例如:Select * from Products</param>
        /// <param name="cmdParms">執行命令的參數</param>
        private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();


            cmd.Connection = conn;
            cmd.CommandText = cmdText;


            if (trans != null)
                cmd.Transaction = trans;


            cmd.CommandType = cmdType;


            if (cmdParms != null)
            {
                foreach (MySqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }


    }

 

三、訪問MySQL數據庫(增刪查改)

提示:sql語句無論是oracle、mysql、sqlserver,增刪查改語句大體相似,皆為insert、delete、update、select操作,故熟悉一種數據庫操作語句後,亦可相對容易學習其他數據庫語句

using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;
using DBUtility;

  

1、插入操作(insert)

示例代碼:

        public int Add( int userId, string name)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO T_Photo(Name,UserID) ");
            sb.Append("VALUES(?Name,?UserID) ");
            MySqlParameter[] parameters = { 
                                             new MySqlParameter("?Name", MySqlDbType.String),
                                             new MySqlParameter("?UserID", MySqlDbType.Int32)
                                         };
            parameters[0].Value = name;
            parameters[1].Value = userId;
            return SQLHelper.ExecuteNonQuery(sb.ToString(), CommandType.Text, parameters);
        }

  

2、刪除操作(delete)

示例代碼:

        public int Delete(long id, int userId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("DELETE FROM T_Photo WHERE ID = ?ID AND UserID = ?UserID");
            MySqlParameter[] parameters = { 
                                             new MySqlParameter("?ID", MySqlDbType.Int64),
                                             new MySqlParameter("?UserID", MySqlDbType.Int32)
                                         };
            parameters[0].Value = id;
            parameters[1].Value = userId;
            return SQLHelper.ExecuteNonQuery(sb.ToString(), CommandType.Text, parameters);
        }

  

3、修改操作(update)

示例代碼:

        public int EditName(long id, int userId, string name)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("UPDATE T_Photo SET Name = ?Name WHERE ID = ?ID AND UserID = ?UserID");
            MySqlParameter[] parameters = { 
                                             new MySqlParameter("?ID", MySqlDbType.Int64),
                                             new MySqlParameter("?UserID", MySqlDbType.Int32),
                                             new MySqlParameter("?Name", MySqlDbType.String)
                                         };
            parameters[0].Value = id;
            parameters[1].Value = userId;
            parameters[2].Value = name;
            return SQLHelper.ExecuteNonQuery(sb.ToString(), CommandType.Text, parameters);
        }

  

4、查詢操作(select)

示例代碼:

        public MySqlDataReader GetListByOrderCode(string orderCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT ID,OrderCount,Subtotal,ProductID, ");
            sb.Append("FROM t_orderdetail  ");


            //篩選條件
            sb.Append("WHERE OrderCode = ?OrderCode ");


            //排序
            sb.Append("ORDER BY ID DESC ");


            MySqlParameter[] parameters = { 
                                             new MySqlParameter("?OrderCode", MySqlDbType.String)
                                         };


            parameters[0].Value = orderCode;
            return SQLHelper.ExecuteReader(sb.ToString(), CommandType.Text, parameters);

        }

  

5、調用存儲過程

示例代碼:

        public int BackOrder(long id)
        {
            StringBuilder sb = new StringBuilder();


            sb.Append("BackOrder ");//存儲過程名稱


            MySqlParameter[] parameters = { 
                                             new MySqlParameter("?OrderId", MySqlDbType.Int64)//OrderId必須與存儲過程參數名、數據類型一致
                                         };
            parameters[0].Value = id;
            return MyCustomSQLHelper.ExecuteNonQuery(sb.ToString(), CommandType.StoredProcedure, parameters);
        }

  

今天就分享到這裡,都是自己積累的心得分享,若有疑問請到http://xunwn.com/1010100聯系我,謝謝,今後也會分享更多給大家

更多分享:http://xunwn.com/photo/1010100

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved