使用Dapper对MySQL进行增删改查

首先使用NuGet添加Dapper和Mysql.Data的引用;

1 using Dapper;
2 using MySql.Data.MySqlClient;

创建数据库表

建立对应的实体类

复制代码
1     public class TestEntity
2     {
3         public int ID { get; set; }
4         public DateTime DateTime { get; set; }
5         public string Name { get; set; }
6         public string PhoneNumber { get; set; }
7         public string Address { get; set; }
8         public string Role { get; set; }
9     }
Entity
复制代码

建立DapperTool类,用以对数据库进行操作:

1 private static string conStr = "server=localhost;database=test;uid=root;pwd=123456";

增删改的函数:

复制代码
 1         /// <summary>
 2         /// 增删改均可
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="sql"></param>
 6         /// <param name="t"></param>
 7         /// <returns></returns>
 8         public static bool Excute<T>(string sql, T t)
 9             where T : class
10         {
11             using (IDbConnection conn = new MySqlConnection(conStr))
12             {
13                 return conn.Execute(sql, t) > 0;
14             }
15         }
Excute
复制代码

批量增删改的函数:

复制代码
 1         /// <summary>
 2         /// 增删改均可[批量]
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="sql"></param>
 6         /// <param name="tlist"></param>
 7         /// <returns></returns>
 8         public static bool Excute<T>(string sql, List<T> tlist)
 9             where T : class
10         {
11             using (IDbConnection conn = new MySqlConnection(conStr))
12             {
13                 return conn.Execute(sql, tlist) > 0;
14             }
15         }
Excute
复制代码

查询函数:

复制代码
 1         /// <summary>
 2         /// 查找
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="sql"></param>
 6         /// <returns></returns>
 7         public static List<T> Query<T>(string sql)
 8             where T : class
 9         {
10             using (IDbConnection conn = new MySqlConnection(conStr))
11             {
12                 return conn.Query<T>(sql).ToList();
13             }
14         }
Query
复制代码

计数函数:

复制代码
 1         /// <summary>
 2         /// 计数
 3         /// </summary>
 4         /// <param name="sql"></param>
 5         /// <returns></returns>
 6         public static int GetCountRow(string sql)
 7         {
 8             using (var connection = new MySqlConnection(conStr))
 9             {
10                 return connection.ExecuteScalar<int>(sql);
11             }
12         }
GetCount
复制代码

分页查询:

复制代码
 1         /// <summary>
 2         /// 分页查询
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="sql"></param>
 6         /// <param name="orderBy"></param>
 7         /// <param name="start"></param>
 8         /// <param name="count"></param>
 9         /// <returns></returns>
10         public static IEnumerable<T> GetPagedData<T>(string sql, string orderBy, int start, int count)
11             where T : class
12         {
13             using (var connection = new MySqlConnection(conStr))
14             {
15                 string pageSql = null;
16                 orderBy = string.IsNullOrEmpty(orderBy) ? " " : string.Format(@" ORDER BY {0} ", orderBy);
17                 pageSql = string.Format(@"{0} {1} LIMIT @StartNum, @RetCount", sql, orderBy);
18                 return connection.Query<T>(pageSql, new { StartNum = start, RetCount = count });
19             }
20         }
GetPageList
复制代码

建立库表类,用以对表进行具体操作:

1 private static string tableName = "personalfile";

添加数据:

复制代码
 1         public static void AddMembers()
 2         {
 3             var list = new List<TestEntity>();
 4             for (int i = 0; i < 5; i++)
 5             {
 6                 list.Add(new TestEntity()
 7                 {
 8                     ID = i,
 9                     DateTime = DateTime.Now.AddDays(0 - i),
10                     Name = "测试" + i,
11                     Address = "地址" + i,
12                     Role = "身份" + i,
13                     PhoneNumber = Math.Pow(2, i).ToString(),
14                     Added = "多余数据"
15                 });
16             }
17             string sql = "Insert into " + tableName + @" (`ID`,`Name`,Role,PhoneNumber,Address,DateTime)
18                         Values
19                         (@ID,@Name,@Role,@PhoneNumber,@Address,@DateTime)";
20             DapperTool.Excute(sql, list);
21         }
Add
复制代码

删除数据:

复制代码
1         public static void Delete()
2         {
3             TestEntity entity = new TestEntity() { ID = 2 };
4             string sql = "Delete From " + tableName + " where `ID`>=@ID";
5             DapperTool.Excute(sql, entity);
6         }
Delete
复制代码

修改数据:

复制代码
1         public static void Update()
2         {
3             List<TestEntity> list = new List<TestEntity>();
4             list.Add(new TestEntity() { ID = 1, Name = "修改Name1" });
5             list.Add(new TestEntity() { ID = 0, Name = "修改Name0" });
6             string sql = "Update " + tableName + " set `Name`=@Name Where `ID`=@ID";
7             DapperTool.Excute(sql, list);
8         }
Update
复制代码

查询数据:

复制代码
1         public static List<TestEntity> Query()
2         {
3             string sql = "Select * From " + tableName + " Where 1=1";
4             return DapperTool.Query<TestEntity>(sql);
5         }
Query
复制代码

查询数量:

复制代码
1         public static int GetCount()
2         {
3             string sql = "Select Count(*) From " + tableName + " where 1=1";
4             return DapperTool.GetCountRow(sql);
5         }
GetCount
复制代码

调用进行验证

复制代码
 1     static void Main(string[] args)
 2     {
 3         //*********************
 4         int count = TestTable.GetCount();
 5         Console.WriteLine("表初始数据数量:" + count);
 6         //*********************
 7         TestTable.AddMembers();
 8         Console.WriteLine("添加5条数据:");
 9         var list = TestTable.Query();
10         list.ForEach(l =>
11         {
12             Console.WriteLine(string.Format("ID:{0} Name:{1} Role:{2} Number:{3} Address:{4}", l.ID, l.Name, l.Role, l.PhoneNumber, l.Address));
13         });
14         //*********************
15         TestTable.Delete();
16         Console.WriteLine("删除数据>=2后:");
17         list = TestTable.Query();
18         list.ForEach(l =>
19         {
20             Console.WriteLine(string.Format("ID:{0} Name:{1} Role:{2} Number:{3} Address:{4}", l.ID, l.Name, l.Role, l.PhoneNumber, l.Address));
21         });
22         //*********************
23         TestTable.Update();
24         Console.WriteLine("更改数据后:");
25         list = TestTable.Query();
26         list.ForEach(l =>
27         {
28             Console.WriteLine(string.Format("ID:{0} Name:{1} Role:{2} Number:{3} Address:{4}", l.ID, l.Name, l.Role, l.PhoneNumber, l.Address));
29         });
30         //*********************
31         Console.ReadLine();
32     }
Main构造函数
复制代码

结果

 

posted @   [春风十里]  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示