Dapper 使用手册
📄字数 1.9K
👁️阅读量 加载中...
Dapper 是一个基于IDbConnection的轻量级扩展,完全依赖ADO.NET原生驱动。 Dapper 的所有操作都建立在标准的 ADO.NET IDbConnection 接口之上,不需要额外提供方言包,本文档只简易描述使用 Dapper 开发 XuguDB 应用的流程。
一、Dapper 连接 XuguDB 示例程序
1.1 环境准备
创建项目
Visual Studio 创建一个控制台新项目 DapperDemo
。
添加 NuGet 包
cs
dotnet add package Dapper
添加 XuguDB .NET 包
通过在线下载链接获取 XuguDB .NET 驱动压缩包,解压后引用XuguClient.dll文件,点击工程中的“引用”,右键选择“添加引用”,单击“浏览”选择文件的位置,最后点击“确定”,之后将xugusql.dll文件存放至用户本地项目组的BIN目录下,与生成的exe可执行文件同级目录。
1.2 代码实现
提前准备好测试表,以下为建表语句:
sql
CREATE TABLE "SYSDBA"."PEOPLE"
(
"ID" INT primary key,
"NAME" CHAR(20),
"EMAIL" CHAR(20)
);
示例代码如下:
cs
using Dapper;
using System.Data;
using XuguClient;
namespace DapperDemo
{
class XgDapper
{
public class XgConnection
{
// XuguDB .NET 驱动连接串
static string ConnectionString = "IP=192.168.2.216;PORT=5138;DB=SYSTEM;USER=SYSDBA;PWD=SYSDBA;CHAR_SET=GBK";
public static IDbConnection GetConn()
{
return new XGConnection(ConnectionString);
}
}
public static void Main()
{
XgDapper dapper = new XgDapper();
People model = new People();
model.Name = "xugu1";
model.Email = "1234567@xugudb.com";
model.Id = 1;
dapper.Add(model);
model = dapper.Get(1);
Console.WriteLine(model.ToString());
List<People> list = dapper.GetList();
foreach (People model2 in list)
{
Console.WriteLine(model2.ToString());
}
model.Name = "xugu";
model.Email = "111111@xugudb.com";
model.Id = 1;
bool a = dapper.Update(model);
Console.WriteLine(a);
bool b = dapper.Delete(2);
Console.WriteLine(b);
}
// 查询单条
public People Get(int id)
{
string sql = "select Id,Name,Email from PEOPLE where Id=:Id";
return XgConnection.GetConn().QueryFirstOrDefault<People>(sql, new { Id = id });
}
// 查询一组数据
public List<People> GetList()
{
string sql = "select Id,Name,Email from PEOPLE";
return XgConnection.GetConn().Query<People>(sql).ToList();
}
// 插入数据
public bool Add(People model)
{
string sql = "insert into PEOPLE(Id,Name,Email) Values(:Id,:Name,:Email);";
int result = XgConnection.GetConn().Execute(sql, model);
return result > 0;
}
// 修改数据
public bool Update(People model)
{
string sql = "update PEOPLE set Email=:Email where Id=:Id";
int result = XgConnection.GetConn().Execute(sql, model);
return result > 0;
}
// 删除数据
public bool Delete(int id)
{
string sql = "delete from PEOPLE where Id=:Id";
int result = XgConnection.GetConn().Execute(sql, new { Id = id });
return result > 0;
}
}
struct People
{
public int Id { set; get; }
public string Name { set; get; }
public string Email { set; get; }
public override string ToString() { return Id + "," + Name + "," + Email; }
}
}
运行结果如下:
txt
1,xugu1,1234567@xugudb.com
1,xugu1,1234567@xugudb.com
True
False
提示
Dapper 具体功能可查看 Dapper 官方文档。