C#视频教程之使用Dapper轻松访问SQL Server数据库(核心源码)
大家好,
我是Rector,一位专注.NET开发者社区建设的.Neter。我之前推出了一个关于《C#视频教程之使用Dapper轻松访问SQL Server数据库》的系列视频讲座。
这个讲座主要面向的对象是C#的初学者或有意愿了解Dapper的小伙伴们,其中涉及到了:
- 什么是Dapper
- 在线数据表及示例数据生成工具
- C#使用Dapper轻松访问SQL Server数据库系列之数据查询操作
- C#使用Dapper轻松访问SQL Server数据库系列之数据写入操作
- C#使用Dapper轻松访问SQL Server数据库系列之数据更新操作
- C#使用Dapper轻松访问SQL Server数据库系列之数据删除操作
本文将为大家提供视频中涉及到的核心源码。
配置文件(App.config)
在Winform程序的配置文件中,我们需要对数据库连接进行配置,具体的数据库连接字符串配置如下:
App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" /> </startup> <connectionStrings> <add name="DbConn" connectionString="Server=.\SQLEXPRESS;Database=SampleData;User Id=sa;Password=123456"/> </connectionStrings> </configuration>
数据库连接帮助类(DbHelper.cs)
数据库连接帮助类是帮助我们从配置文件中读取数据库的连接字符串的,其中包含了一个静态的返回类型为 string
的属性,通过这个属性,我们可以获取到当前应用程序配置的数据库连接字符串,具体代码如下:
DbHelper.cs
using System.Configuration; namespace DapperDemo { /// <summary> /// 数据库连接帮助类 /// </summary> public class DbHelper { /// <summary> /// 从配置文件中读取数据库连接字符串 /// </summary> public static string ConnctionString { get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } } } }
用户实体类(Person.cs)
用户实体类:本次示例程序中涉及到的用户类,包含了用户的一些基本信息,具体如下:
Person.cs
using System; namespace DapperDemo { /// <summary> /// 用户信息实体类 /// </summary> public class Person { /// <summary> /// 自增ID /// </summary> public int Id { get; set; } /// <summary> /// 名字 /// </summary> public string FirstName { get; set; } /// <summary> /// 姓氏 /// </summary> public string LastName { get; set; } /// <summary> /// 电子邮箱 /// </summary> public string EmailAddress { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreatedOn { get; set; } /// <summary> /// IP地址 /// </summary> public string IpAddress { get; set; } /// <summary> /// 计算属性,返回用户的详细 /// </summary> public string Display { get { return $"{FirstName} {LastName} ({EmailAddress}) {IpAddress}"; } } } }
用户信息服务类(PersonService.cs)
用户信息服务类:主要负责使用Dapper与数据库进行交互,其中包含的操作有简单的数据增、删、改、查等,具体的实现代码如下:
PersonService.cs
using Dapper; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; namespace DapperDemo { /// <summary> /// 用户信息服务类 /// </summary> public class PersonService { /// <summary> /// 根据用户姓氏查询用户集合 /// </summary> /// <param name="lastName">姓氏</param> /// <returns></returns> public List<Person> FindListByLastName(string lastName) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = $"SELECT * FROM Person WHERE LastName=@LastName"; IEnumerable<Person> list = db.Query<Person>(sql, new { LastName = lastName }); return list.ToList(); } } /// <summary> /// 写入用户信息 /// </summary> /// <param name="person">用户实体</param> /// <returns></returns> public bool Insert(Person person) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "INSERT INTO Person (FirstName,LastName,EmailAddress) VALUES (@FirstName,@LastName,@EmailAddress)"; int result = db.Execute(sql, person); return result > 0; } } /// <summary> /// 根据用户ID查询用户信息 /// </summary> /// <param name="personId">用户ID</param> /// <returns></returns> public Person FindById(int personId) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "SELECT * FROM Person WHERE Id=@Id"; IEnumerable<Person> list = db.Query<Person>(sql, new { Id = personId }); return list.FirstOrDefault(); } } /// <summary> /// 更新用户信息 /// </summary> /// <param name="person">用户实体</param> /// <returns></returns> public bool Update(Person person) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "UPDATE Person SET FirstName=@FirstName,LastName=@LastName,EmailAddress=@EmailAddress WHERE Id=@Id"; int result = db.Execute(sql, person); return result > 0; } } /// <summary> /// 删除用户信息 /// </summary> /// <param name="personId">用户ID</param> /// <returns></returns> public bool Delete(int personId) { using (IDbConnection db = new SqlConnection(DbHelper.ConnctionString)) { string sql = "DELETE FROM Person WHERE Id=@Id"; int result = db.Execute(sql, new { Id = personId }); return result > 0; } } } }
仪表盘后端实现(Dashboard.cs)
最后,是我们的仪表盘后端代码,包含了示例中涉及中的增、删、改、查等事件对应的方法实现,如下:
Dashboard.cs
using System; using System.Collections.Generic; using System.Windows.Forms; namespace DapperDemo { public partial class Dashboard : Form { public Dashboard() { InitializeComponent(); } private void btnSearch_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); List<Person> result = ps.FindListByLastName(txtSearchLastName.Text); lstSearchResult.DataSource = result; lstSearchResult.DisplayMember = "Display"; } private void btnCreate_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); //person.FirstName = txtFrmFirstName.Text; //person.LastName = txtFrmLastName.Text; //person.EmailAddress = txtFrmEmailAddress.Text; Person person = new Person { FirstName = txtFrmFirstName.Text, LastName = txtFrmLastName.Text, EmailAddress = txtFrmEmailAddress.Text }; bool success = ps.Insert(person); MessageBox.Show(success ? "操作成功" : "操作失败"); } private void btnIndex_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); int personId = Convert.ToInt32(txtIndexPersonId.Text); Person person = ps.FindById(personId); txtFrmFirstName.Text = person.FirstName; txtFrmLastName.Text = person.LastName; txtFrmEmailAddress.Text = person.EmailAddress; } private void btnUpdate_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); Person person = new Person { Id = Convert.ToInt32(txtIndexPersonId.Text), FirstName = txtFrmFirstName.Text, LastName = txtFrmLastName.Text, EmailAddress = txtFrmEmailAddress.Text }; bool success = ps.Update(person); MessageBox.Show(success ? "操作成功" : "操作失败"); } private void btnDelete_Click(object sender, EventArgs e) { PersonService ps = new PersonService(); int personId = Convert.ToInt32(txtIndexPersonId.Text); bool success = ps.Delete(personId); MessageBox.Show(success ? "操作成功" : "操作失败"); } } }
视频教程中分享的两个网址:
- 在线随机数据生成工具:https://www.mockaroo.com/
- 在线.NET数据库连接配置文档:https://www.connectionstrings...
希望对大家有所帮助,谢谢。
如果有学习过程中遇到任何问题,请加我们的.NET开发者社区学习交流群:483350228
相关推荐
架构技术交流 2020-05-02
Iamthedoctor 2020-05-10
sunzxh 2020-05-10
Iamthedoctor 2020-05-02
步行者 2020-05-02
LeonZhang0 2019-12-16
86523296 2019-10-19
piaoman0 2014-08-15
KOJ 2019-07-01
TWITTER自行车符R 2016-06-12
蔷薇部落 2019-04-26
功夫熊猫 2019-06-28
zyjj 2019-06-27
兔子压倒窝边草 2019-06-25
lovejk 2019-06-22
ASAformairuan 2019-03-24
zhlflylinux 2010-06-28
ParrySMS 2018-03-29