亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#操作MySql的方法是什么

發布時間:2023-03-20 10:13:19 來源:億速云 閱讀:111 作者:iii 欄目:開發技術

這篇文章主要講解了“C#操作MySql的方法是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C#操作MySql的方法是什么”吧!

    代碼介紹

    功能包含:

    • 創建數據庫

    • 創建數據表

    • 批量添加數據

    • MySql事務執行

    • 清表

    • 分頁、模糊查詢

    代碼實現

    創建數據庫

    public void CreateDatabase(string sqlStr)
    {
        string str = $"Server=localhost;User=root;Password=123456;CharSet=UTF8;";
        using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnection))
        {
            mySqlConnection.Open();
            try 
            {
                MySqlCommand cmd = new MySqlCommand(sqlStr, mySqlConnection);
                cmd.ExecuteNonQuery();
            } catch(Exception e) 
            {
                Debug.Log(e.Message.ToString());
            }
            finally
            {
                mySqlConnection.Close();
            }
        }
    }

    創建數據表

    private static void CteateDataTable(string sqlStr)
    {
        using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
        {
            mySqlConnection.Open();
            MySqlCommand cmd = new MySqlCommand(sqlStr, mySqlConnection);
            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                mySqlConnection.Close();
            }
        }
    }

    查詢數據

    private static DataTable SelectTable(string sqlStr)
    {
        DataTable dt = new DataTable();
        using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
        {
            mySqlConnection.Open();
            try
            {
                MySqlDataAdapter da = new MySqlDataAdapter(sqlStr, mySqlConnection);
                da.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                mySqlConnection.Close();
            }
        }
    }

    事務

    private static bool ExecuteSqlTransaction(string sqlStr)
    {
        using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
        {
            mySqlConnection.Open();
            MySqlCommand cmd = mySqlConnection.CreateCommand();
            cmd.Connection = mySqlConnection;
            MySqlTransaction sqlTransaction = mySqlConnection.BeginTransaction();
            try
            {
                cmd.CommandText = sqlStr;
                cmd.ExecuteNonQuery();
                sqlTransaction.Commit();
                sqlTransaction = mySqlConnection.BeginTransaction();
                return true;
            }
            catch (Exception ex)
            {
                sqlTransaction.Rollback();
                return false;
            }
            finally
            {
                mySqlConnection.Close();
            }
        };
    }

    代碼示例

    using MySql.Data.MySqlClient;
    using Newtonsoft.Json;
    using NPinyin;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.IO;
    using System.Text;
    
    namespace ConsoleApp1
    {
        internal class Program
        {
            private static string mySqlConnectStr = ConfigurationManager.AppSettings["connectionStr"];
    
            static void Main(string[] args)
            {
                CreateDatabase("CREATE DATABASE DataBaseName;");
    
                CreateTable();
    
                SQLCMD();
    
                DeleteTableDataAll();
    
                var drugData = SelectTable(@"SELECT * FROM `t_drugs` WHERE t_drugs.drug_name_py LIKE ""%PT%"" LIMIT 1,10;");
    
                List<Drug> drugs = new List<Drug>();
                foreach (DataRow item in drugData.Rows)
                {
                    drugs.Add(new Drug
                    {
                        hospital_no = item["hospital_no"].ToString(),
                        hospital_name = item["hospital_name"].ToString(),
                        drug_id = item["drug_id"].ToString(),
                        drug_name = item["drug_name"].ToString(),
                        drug_type = item["drug_type"].ToString(),
                        drug_short = item["drug_short"].ToString(),
                        sizes = item["sizes"].ToString(),
                        unit = item["unit"].ToString(),
                        price = item["price"].ToString(),
                        money_type = item["money_type"].ToString(),
                        producer = item["producer"].ToString(),
                        dose = item["dose"].ToString(),
                        usage = item["usage"].ToString(),
                        summary = item["summary"].ToString(),
                        ext = item["ext"].ToString(),
                    });
                }
    
                DataTable projectData = SelectTable(@"SELECT * FROM `t_project` WHERE t_project.item_name_py LIKE ""%PT%"" LIMIT 1,10;");
    
                List<Project> project = new List<Project>();
                foreach (DataRow item in projectData.Rows)
                {
                    project.Add(new Project
                    {
                        hospital_no = item["hospital_no"].ToString(),
                        hospital_name= item["hospital_name"].ToString(),
                        item_id = item["item_id"].ToString(),
                        item_name = item["item_name"].ToString(),
                        item_type = item["item_type"].ToString(),
                        item_short = item["item_short"].ToString(),
                        sizes = item["sizes"].ToString(),
                        unit = item["unit"].ToString(),
                        price = item["price"].ToString(),
                        money_type = item["money_type"].ToString(),
                        ext = item["ext"].ToString(),
                    });
                }
    
                Console.ReadKey();
            }
    
            public void CreateDatabase(string sqlStr)
            {
                string str = $"Server=localhost;User=root;Password=123456;CharSet=UTF8;";
                using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnection))
                {
                    mySqlConnection.Open();
                    try 
                    {
                        MySqlCommand cmd = new MySqlCommand(sqlStr, mySqlConnection);
                        cmd.ExecuteNonQuery();
                    } catch(Exception e) 
                    {
                        Debug.Log(e.Message.ToString());
                    }
                    finally
                    {
                        mySqlConnection.Close();
                    }
                }
    	    } 
    
            private static DataTable SelectTable(string sqlStr)
            {
                DataTable dt = new DataTable();
                using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
                {
                    mySqlConnection.Open();
                    try
                    {
                        MySqlDataAdapter da = new MySqlDataAdapter(sqlStr, mySqlConnection);
                        da.Fill(dt);
                        return dt;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        mySqlConnection.Close();
                    }
                }
            }
    
            /// <summary>
            /// 執行 插入藥品、項目數據
            /// </summary>
            private static void SQLCMD()
            {
                #region 藥品
    
                var drugjsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"drug.json");
                var drugJsonStr = File.ReadAllText(drugjsonPath);
                Rootobject<List<Drug>> drugs = JsonConvert.DeserializeObject<Rootobject<List<Drug>>>(drugJsonStr);
                string drugSql = @"INSERT INTO T_drugs (drug_id,drug_name,drug_type,sizes,unit,price,money_type,producer) VALUE ";
                foreach (var drug in drugs.data)
                {
                    drugSql += $"(\"{drug.drug_id}\",\"{drug.drug_name}\",\"{drug.drug_type}\",\"{drug.sizes}\",\"{drug.unit}\",\"{drug.price}\",\"{drug.money_type}\",\"{drug.producer}\"),";
                }
                drugSql = $"{drugSql.Remove(drugSql.Length - 1, 1)};";
                if (ExecuteSqlTransaction(drugSql))
                {
                    Console.WriteLine("執行成功!");
                }
                else
                {
                    Console.WriteLine("執行失敗!");
                }
    
                #endregion
    
                #region 項目
    
                var projectjsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"project.json");
                var projectJsonStr = File.ReadAllText(projectjsonPath);
                Rootobject<List<Project>> projects = JsonConvert.DeserializeObject<Rootobject<List<Project>>>(projectJsonStr);
                string projectSql = @"INSERT INTO T_project (item_id,item_name,unit,price) VALUE ";
                foreach (var project in projects.data)
                {
                    projectSql += $"(\"{project.item_id}\",\"{project.item_name}\",\"{project.unit}\",\"{project.price}\"),";
                }
                projectSql = $"{projectSql.Remove(projectSql.Length - 1, 1)};";
                if (ExecuteSqlTransaction(projectSql))
                {
                    Console.WriteLine("執行成功!");
                }
                else
                {
                    Console.WriteLine("執行失敗!");
                }
                #endregion
            }
    
            /// <summary>
            /// 創建 藥品、項目表
            /// </summary>
            private static void CreateTable()
            {
                string t_drugSql = @"USE xzd;
                                    CREATE TABLE IF NOT EXISTS T_drugs
                                    (
    	                                `hospital_no` VARCHAR(20),
    	                                `hospital_name` VARCHAR(50),
    	                                `drug_id` VARCHAR(50),
    	                                `drug_name` VARCHAR(50),
    	                                `drug_name_py` VARCHAR(50),
    	                                `drug_type` VARCHAR(10),
    	                                `drug_short` VARCHAR(10),
    	                                `sizes` VARCHAR(10),
    	                                `unit` VARCHAR(10),
    	                                `price` VARCHAR(10),
    	                                `money_type` VARCHAR(50),
    	                                `producer` VARCHAR(100),
    	                                `dose` VARCHAR(10),
    	                                `usage` VARCHAR(10),
    	                                `summary` VARCHAR(50),
    	                                `ext` VARCHAR(50)
                                    )ENGINE=INNODB DEFAULT CHARSET=utf8;";
    
                string t_project = @"USE xzd;
                                    CREATE TABLE IF NOT EXISTS T_project
                                    (
                                     `hospital_no` VARCHAR(20),
                                     `hospital_name` VARCHAR(50),
                                     `item_id` VARCHAR(50),
                                     `item_name` VARCHAR(50),
                                     `item_name_py` VARCHAR(50),
                                     `item_type` VARCHAR(10),
                                     `item_short` VARCHAR(10),
                                     `sizes` VARCHAR(10),
                                     `unit` VARCHAR(30),
                                     `price` VARCHAR(10),
                                     `money_type` VARCHAR(50),
                                     `ext` VARCHAR(50)
                                    )ENGINE=INNODB DEFAULT CHARSET=utf8;";
    
    
                CteateDataTable(t_drugSql);
                CteateDataTable(t_project);
            }
    
            /// <summary>
            /// 執行創建表sql
            /// </summary>
            /// <param name="sqlStr"></param>
            private static void CteateDataTable(string sqlStr)
            {
                using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
                {
                    mySqlConnection.Open();
                    MySqlCommand cmd = new MySqlCommand(sqlStr, mySqlConnection);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        mySqlConnection.Close();
                    }
                }
            }
    
            /// <summary>
            /// mysql事務
            /// </summary>
            /// <param name="sqlStr"></param>
            /// <exception cref="Exception"></exception>
            private static bool ExecuteSqlTransaction(string sqlStr)
            {
                using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
                {
                    mySqlConnection.Open();
                    MySqlCommand cmd = mySqlConnection.CreateCommand();
                    cmd.Connection = mySqlConnection;
    
                    MySqlTransaction sqlTransaction = mySqlConnection.BeginTransaction();
                    try
                    {
                        cmd.CommandText = sqlStr;
                        cmd.ExecuteNonQuery();
                        sqlTransaction.Commit();
                        sqlTransaction = mySqlConnection.BeginTransaction();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        sqlTransaction.Rollback();
                        return false;
                    }
                    finally
                    {
                        mySqlConnection.Close();
                    }
                };
    
            }
    
            /// <summary>
            /// 刪除表所有數據
            /// </summary>
            /// <returns></returns>
            private static bool DeleteTableDataAll()
            {
                string sqlStr = @"DELETE FROM T_drugs; DELETE FROM T_project;";
                using (MySqlConnection mySqlConnection = new MySqlConnection(mySqlConnectStr))
                {
                    mySqlConnection.Open();
                    MySqlCommand cmd = new MySqlCommand(sqlStr, mySqlConnection);
                    try
                    {
                        cmd.ExecuteNonQuery();                   
                        return true;
                    }
                    catch (Exception ex)
                    {
                        return false;
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        mySqlConnection.Close();
                    }
                }
            }
        }
    
        #region 實體
    
        /// <summary>
        /// 包裝類
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class Rootobject<T>
        {
            public string code { get; set; }
            public T data { get; set; }
        }
    
        /// <summary>
        /// 藥品
        /// </summary>
        public class Drug
        {
            public string hospital_no { get; set; }
            public string hospital_name { get; set; }
            public string drug_id { get; set; }
            public string drug_name { get; set; }
            public string drug_type { get; set; }
            public string drug_short { get; set; }
            public string sizes { get; set; }
            public string unit { get; set; }
            public string price { get; set; }
            public string money_type { get; set; }
            public string producer { get; set; }
            public string dose { get; set; }
            public string usage { get; set; }
            public string summary { get; set; }
            public string ext { get; set; }
        }
    
        /// <summary>
        /// 項目
        /// </summary>
        public class Project
        {
            public string hospital_no { get; set; }
            public string hospital_name { get; set; }
            public string item_id { get; set; }
            public string item_name { get; set; }
            public string item_type { get; set; }
            public string item_short { get; set; }
            public string sizes { get; set; }
            public string unit { get; set; }
            public string price { get; set; }
            public string money_type { get; set; }
            public string ext { get; set; }
        }
    
        #endregion
    }

    感謝各位的閱讀,以上就是“C#操作MySql的方法是什么”的內容了,經過本文的學習后,相信大家對C#操作MySql的方法是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

    向AI問一下細節

    免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

    AI

    黄山市| 搜索| 清水县| 明光市| 新平| 襄樊市| 凤城市| 夹江县| 临泉县| 金塔县| 齐齐哈尔市| 岳阳县| 纳雍县| 横山县| 阜平县| 吉安市| 湖南省| 耒阳市| 卫辉市| 崇仁县| 宜黄县| 公主岭市| 玉山县| 正蓝旗| 崇义县| 金坛市| 昌黎县| 沙河市| 洱源县| 荔波县| 横峰县| 金秀| 云霄县| 云林县| 枞阳县| 锦屏县| 南京市| 陆河县| 鲜城| 岢岚县| 黄冈市|