1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關咨詢
      選擇下列產(chǎn)品馬上在線溝通
      服務時間:8:30-17:00
      你可能遇到了下面的問題
      關閉右側工具欄

      新聞中心

      這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
      怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫-創(chuàng)新互聯(lián)

      這期內(nèi)容當中小編將會給大家?guī)碛嘘P怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

      創(chuàng)新互聯(lián)建站網(wǎng)站建設服務商,為中小企業(yè)提供成都網(wǎng)站設計、做網(wǎng)站、成都外貿(mào)網(wǎng)站建設公司服務,網(wǎng)站設計,綿陽服務器托管等一站式綜合服務型公司,專業(yè)打造企業(yè)形象網(wǎng)站,讓您在眾多競爭對手中脫穎而出創(chuàng)新互聯(lián)建站

      引入MySql.Data 的Nuget包。有人可能出現(xiàn)了黑人臉,怎么引入。也罷,看在你骨骼驚奇的份上,我就告訴你,兩種方式:


      第一種方式

      Install-Package MySql.Data -Version 8.0.15

      復制上面命令行 在程序包管理控制臺中執(zhí)行,什么?你不知道什么是程序包管理控制臺?OMG,也罷,看在你骨骼驚奇的份上,我就告訴你

      手點路徑:工具 → NuGet包管理器 → 程序包管理控制臺

      怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫

      第二種方式

      手點路徑:右鍵你需要引入包的項目的依賴項 → 管理NuGet程序包 → 瀏覽里面輸入 MySql.Data

      怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫

      怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫

      直接安裝即可,因為我已經(jīng)安裝過了,所以這里是卸載或者更新

      同樣的方式你需要引入:

      Microsoft.AspNetCore.All
      MySql.Data.EntityFrameworkCore、
      Dapper
      Microsoft.Extensions.Configuration.Abstractions
      Microsoft.Extensions.Configuration.FileExtensions
      Microsoft.Extensions.Configuration.Json

      教學篇

      玩兒過.NET Core 的都知道配置文件我們一般都放在appsettings.json 文件中,但是有個問題,如果我們使用數(shù)據(jù)庫連接字符串,直接存放明文的user name和password,真的安全嗎?這里我們不對安全性做討論,我們在連接字符串中 用占位符控制我們的多數(shù)據(jù)庫情況,然后用userName以及passWord充當我們密碼(后面會被替換掉),所以看起來是這個樣子:

       "ConnectionStrings": {
        "DefaultConnection": "server=服務器;port=端口號;database=regatta{0};SslMode=None;uid=userName;pwd=passWord;Allow User Variables=true"
       },

      接下來,我們新建一個BaseRepository 用于讀取Configuration,以及設置MySqlConnection:

      public class BaseRepository : IDisposable
        {
          public static IConfigurationRoot Configuration { get; set; }
      
          private MySqlConnection conn;
      
          public MySqlConnection GetMySqlConnection(int regattaId = 0, bool open = true,
            bool convertZeroDatetime = false, bool allowZeroDatetime = false)
          {
            IConfigurationBuilder builder = new ConfigurationBuilder()
              .SetBasePath(Directory.GetCurrentDirectory())
              .AddJsonFile("appsettings.json");
      
            Configuration = builder.Build();
            
      
            string cs = Configuration.GetConnectionString("DefaultConnection");
            cs = regattaId == 0 ? string.Format(cs, string.Empty) : string.Format(cs, "_" + regattaId.ToString());
      
            cs = cs.Replace("userName", "真正的賬號").Replace("passWord", "真正的密碼");
            var csb = new MySqlConnectionStringBuilder(cs)
            {
              AllowZeroDateTime = allowZeroDatetime,
              ConvertZeroDateTime = convertZeroDatetime
            };
            conn = new MySqlConnection(csb.ConnectionString);
            return conn;
          }
      public void Dispose()
      {
      if (conn != null && conn.State != System.Data.ConnectionState.Closed)
      {
      conn.Close();
      }
      }
      
      }

      好了,創(chuàng)建完畢,我們該如何使用呢,比方說 現(xiàn)在有個CrewManagerRepository類用于操作數(shù)據(jù)庫,我們只需要讓此類繼承BaseRepository , 示例如下

        /// 
          /// 根據(jù)賽事Id、用戶Id獲取用戶基本信息
          /// 
          /// 賽事Id
          /// 用戶Id
          /// 
          public async Task<實體對象> FindUserByAccount(int regattaId, int userId)
          {
            try
            {
              var cmdText =
                @"select b.id_number as IdentifierId,b.isvalid as Isvalid,a.name as Name,a.userid as InternalId,a.sex as Sexual,a.sex as SexTypeId,a.age as Age,
                      c.isprofessional as IsProfessional,c.role_type as RoleTypeId,a.weight as Weight,a.height as Height, a.phone as PhoneNumber,a.thumb_image as ThubmnailImage,
                      a.image as Image,c.athlete_id as AthleteId from 表1 a left join 表2 b on a.userid=b.id 
                      left join 表3 c on b.id=c.centralid where a.userid=@userId;";
                //此處可以根據(jù)傳入的regattaId訪問不同的數(shù)據(jù)庫
              using (var conn = GetMySqlConnection(regattaId))
              {
                if (conn.State == ConnectionState.Closed)
                {
                  await conn.OpenAsync();
                }
      
                var memberModel = conn
                  .Query<實體對象>(cmdText, new { userId = userId }, commandType: CommandType.Text)
                  .FirstOrDefault();
                return memberModel ?? new MemberDetail();
              }
            }
            catch (Exception ex)
            {
              _logger.LogError(ex, "FindUserByAccount by Id Failed!");
              throw;
            }
      
      
          }

      那有同學可能有黑人臉出現(xiàn)了,如果需要事務呢(露出嘴角的微笑)?

      public async Task DeleteXXX(int regattaId, int id, int userId)
          {
            var result = false;
            using (var conn = GetMySqlConnection(regattaId))
            {
              if (conn.State == ConnectionState.Closed)
              {
                await conn.OpenAsync();
              }
      
              using (var transaction = conn.BeginTransaction())
              {
                try
                {
                  const string sqlDelClub =
                    @"delete from 表名 where 字段1=@clubId;
                     delete from 表名2 where 字段2=@clubId;
                     delete from 表名3 where 字段3=@userId and clubinfo_id=@clubId;";
      
                  await conn.QueryAsync(sqlDelClub, new
                  {
                    clubId = id,
                    userId = userId,
                  }, commandType: CommandType.Text);
      
                  transaction.Commit();
      
                  result = true;
                }
                catch (Exception e)
                {
                  Console.WriteLine(e);
                  transaction.Rollback();
                  result = false;
                  throw;
                }
              }
      
              return result;
            }
          }

      這樣,用Transaction將執(zhí)行代碼塊包起來,如果出現(xiàn)異常,在catch中 進行Rollback(回滾事務),就可以保證了數(shù)據(jù)的一致性。如果是高并發(fā)場景,可能還會需要用到鎖,這里暫時不做延伸討論。

      如果是返回集合,也很容易處理:

      public async Task> GetClubsByUserId(int regattaId, int userId)
          {
            using (var conn = GetMySqlConnection(regattaId))
            {
              if (conn.State == ConnectionState.Closed)
              {
                await conn.OpenAsync();
              }
      
              const string sql =
                @"select b.club_id as id,c.name,c.image as ImageData,c.year,c.address,c.creator,c.description,b.contact ,b.phone,b.isvalid from 表1 a left join 表2 b on 
                 a.clubinfo_id=b.club_id left join 表3 c on 
                 b.clubbase_id=c.club_id where a.authorize_userid=@user_Id";
              List<實體> clubDetailList =
                (await conn.QueryAsync<實體>(sql, new { user_Id = userId }, commandType: CommandType.Text))
                .ToList();
      
              return clubDetailList;
            }
          }

      上述就是小編為大家分享的怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。


      文章標題:怎么在.NET中使用Dapper操作mysql數(shù)據(jù)庫-創(chuàng)新互聯(lián)
      本文地址:http://www.ef60e0e.cn/article/djsddo.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        将乐县| 拉孜县| 五指山市| 万盛区| 兴山县| 永安市| 马尔康县| 丽水市| 平潭县| 建始县| 襄城县| 新民市| 南投市| 泸水县| 绥宁县| 河东区| 鹤峰县| 阳新县| 紫阳县| 长治市| 赤水市| 樟树市| 乌拉特中旗| 汝州市| 渝北区| 津南区| 仲巴县| 萍乡市| 顺义区| 皮山县| 武汉市| 宁陕县| 中卫市| 临猗县| 铜山县| 杭锦后旗| 淅川县| 乌拉特中旗| 浦县| 临夏县| 镇江市|