- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章.NET Core Dapper操作mysql数据库的实现方法由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
前言 。
现在ORM盛行,市面上已经出现了N款不同的ORM套餐了。今天,我们不谈EF,也不聊神马黑马,就说说 Dapper。如何在.NET Core中使用Dapper操作Mysql数据库呢,让我们跟随镜头(手动下翻)一看究竟.
配置篇 。
俗话说得好,欲要善其事必先利其器。首先,我们要引入MySql.Data 的Nuget包。有人可能出现了黑人脸,怎么引入。也罢,看在你骨骼惊奇的份上,我就告诉你,两种方式:
第一种方式 。
1
|
Install-Package MySql.Data -Version 8.0.15
|
复制上面命令行 在程序包管理控制台中执行,什么?你不知道什么是程序包管理控制台?OMG,也罢,看在你骨骼惊奇的份上,我就告诉你 。
手点路径:工具 → NuGet包管理器 → 程序包管理控制台 。
第二种方式 。
手点路径:右键你需要引入包的项目的依赖项 → 管理NuGet程序包 → 浏览里面输入 MySql.Data 。
直接安装即可,因为我已经安装过了,所以这里是卸载或者更新 。
同样的方式你需要引入:
1
2
3
4
5
6
|
Microsoft.AspNetCore.All
MySql.Data.EntityFrameworkCore、
Dapper
Microsoft.Extensions.Configuration.Abstractions
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
|
教学篇 。
玩儿过.NET Core 的都知道配置文件我们一般都放在appsettings.json 文件中,但是有个问题,如果我们使用数据库连接字符串,直接存放明文的user name和password,真的安全吗?这里我们不对安全性做讨论,我们在连接字符串中 用占位符控制我们的多数据库情况,然后用userName以及passWord充当我们密码(后面会被替换掉),所以看起来是这个样子:
1
2
3
|
"ConnectionStrings"
: {
"DefaultConnection"
:
"server=服务器;port=端口号;database=regatta{0};SslMode=None;uid=userName;pwd=passWord;Allow User Variables=true"
},
|
接下来,我们新建一个BaseRepository 用于读取Configuration,以及设置MySqlConnection:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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();
}
}
}
|
好了,创建完毕,我们该如何使用呢,比方说 现在有个CrewManagerRepository类用于操作数据库,我们只需要让此类 继承BaseRepository , 示例如下 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
/// <summary>
/// 根据赛事Id、用户Id获取用户基本信息
/// </summary>
/// <param name="regattaId">赛事Id</param>
/// <param name="userId">用户Id</param>
/// <returns></returns>
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;"
;
//此处可以根据传入的regattaId访问不同的数据库
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
;
}
}
|
那有同学可能有黑人脸出现了,如果需要事务呢(露出嘴角的微笑)?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public
async Task<
bool
> 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将执行代码块包起来,如果出现异常,在catch中 进行Rollback(回滚事务),就可以保证了数据的一致性。如果是高并发场景,可能还会需要用到锁,这里暂时不做延伸讨论.
如果是返回集合,也很容易处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public
async Task<List<实体>> 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;
}
}
|
关于Dapper的示例 本文就讲到这儿,大家可以上官网浏览了解更多:
https://dapper-tutorial.net/ 。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我.
原文链接:http://www.cnblogs.com/zhangxiaoyong/p/10765693.html 。
最后此篇关于.NET Core Dapper操作mysql数据库的实现方法的文章就讲到这里了,如果你想了解更多关于.NET Core Dapper操作mysql数据库的实现方法的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我想了解 Ruby 方法 methods() 是如何工作的。 我尝试使用“ruby 方法”在 Google 上搜索,但这不是我需要的。 我也看过 ruby-doc.org,但我没有找到这种方法。
Test 方法 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。 object.Test(string) 参数 object 必选项。总是一个
Replace 方法 替换在正则表达式查找中找到的文本。 object.Replace(string1, string2) 参数 object 必选项。总是一个 RegExp 对象的名称。
Raise 方法 生成运行时错误 object.Raise(number, source, description, helpfile, helpcontext) 参数 object 应为
Execute 方法 对指定的字符串执行正则表达式搜索。 object.Execute(string) 参数 object 必选项。总是一个 RegExp 对象的名称。 string
Clear 方法 清除 Err 对象的所有属性设置。 object.Clear object 应为 Err 对象的名称。 说明 在错误处理后,使用 Clear 显式地清除 Err 对象。此
CopyFile 方法 将一个或多个文件从某位置复制到另一位置。 object.CopyFile source, destination[, overwrite] 参数 object 必选
Copy 方法 将指定的文件或文件夹从某位置复制到另一位置。 object.Copy destination[, overwrite] 参数 object 必选项。应为 File 或 F
Close 方法 关闭打开的 TextStream 文件。 object.Close object 应为 TextStream 对象的名称。 说明 下面例子举例说明如何使用 Close 方
BuildPath 方法 向现有路径后添加名称。 object.BuildPath(path, name) 参数 object 必选项。应为 FileSystemObject 对象的名称
GetFolder 方法 返回与指定的路径中某文件夹相应的 Folder 对象。 object.GetFolder(folderspec) 参数 object 必选项。应为 FileSy
GetFileName 方法 返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。 object.GetFileName(pathspec) 参数 object 必选项。应为
GetFile 方法 返回与指定路径中某文件相应的 File 对象。 object.GetFile(filespec) 参数 object 必选项。应为 FileSystemObject
GetExtensionName 方法 返回字符串,该字符串包含路径最后一个组成部分的扩展名。 object.GetExtensionName(path) 参数 object 必选项。应
GetDriveName 方法 返回包含指定路径中驱动器名的字符串。 object.GetDriveName(path) 参数 object 必选项。应为 FileSystemObjec
GetDrive 方法 返回与指定的路径中驱动器相对应的 Drive 对象。 object.GetDrive drivespec 参数 object 必选项。应为 FileSystemO
GetBaseName 方法 返回字符串,其中包含文件的基本名 (不带扩展名), 或者提供的路径说明中的文件夹。 object.GetBaseName(path) 参数 object 必
GetAbsolutePathName 方法 从提供的指定路径中返回完整且含义明确的路径。 object.GetAbsolutePathName(pathspec) 参数 object
FolderExists 方法 如果指定的文件夹存在,则返回 True;否则返回 False。 object.FolderExists(folderspec) 参数 object 必选项
FileExists 方法 如果指定的文件存在返回 True;否则返回 False。 object.FileExists(filespec) 参数 object 必选项。应为 FileS
我是一名优秀的程序员,十分优秀!