对应Demo程序名:DapperDemo
准备工作:为项目安装Dapper类库
方法一:项目中添加:项目名右键;Manage NuGet Packages;搜索Dappe;点击安装
方法二:在NuGet官网(https://www.nuget.org/)查询类库的安装命令:
搜索Dapper;找到安装命令(Install-Package Dapper -Version 1.60.6);在Visual Studio中打开包管理工具控制台(Tools→NuGget Package Manager→Packages Manager Console);
选中默认的项目(DapperDemo)并输入安装命令;回车
一、创建实体类,例如Person.cs
作用:Person类对应数据库中的Person表,各字段对应数据库表的各列。
1 public class Person 2 { 3 public int Id { get; set; } 4 public string FirstName { get; set; } 5 public string LastName { get; set; } 6 public string EmailAddress { get; set; } 7 public DateTime CreatedOn { get; set; } 8 public string IpAddress { get; set; } 9 10 //定义一个属性,用来计算所有属性 11 /// <summary> 12 /// 计算属性,返回用户的详细信息 13 /// </summary> 14 public string Display 15 { 16 get 17 { 18 return $"{FirstName} {LastName} ({EmailAddress}) {IpAddress}"; 19 } 20 } 21 }
二、创建数据库连接帮助类DbHelper.cs
作用:从配置文件中读取数据库连接字符串。
1 public class DbHelper 2 { 3 /// <summary> 4 /// 从配置文件中读取数据库连接字符串 5 /// </summary> 6 public static string ConnectionString 7 { 8 get { return ConfigurationManager.ConnectionStrings["Dbconn"].ConnectionString; } 9 } 10 }
注:解决ConfigurationManager标红:添加引用Reference→Add Reference→System.Configuration,再在程序中引用using System.Configuration;
三、数据库连接配置(App.config)
作用:在配置文件中存放数据库连接信息,如需修改,只修改配置文件而不用修改源代码,符合开闭原则。
在<configuration>节点下添加<connectionStrings>节点,存放数据库连接信息:
1 <configuration> 2 <connectionStrings> 3 <add name="Dbconn" connectionString="Server=127.0.0.1;Database=master;User Id=sa;Password=Phoenix@2019;" /> 4 </connectionStrings> 5 </configuration>
四、创建数据库访问类PersonService.cs
作用:连接并访问数据库,读取或写入到数据库。
1 public class PersonService 2 { 3 /// <summary> 4 /// 根据用户姓氏查询用户集合 5 /// </summary> 6 /// <param name="lastName">姓氏</param> 7 /// <returns></returns> 8 public List<Person> FindListByLastName(string lastName) 9 { 10 //SELECT * FROM Person WHERE LastName='Pye' 11 using (IDbConnection db = new SqlConnection(DbHelper.ConnectionString)) 12 { 13 //where后直接跟变量来查询,不能避免SQL注入,应使用后边一种写法 14 //string sql = $"SELECT * FROM Person WHERE LastName='{lastName}'"; 15 //IEnumerable<Person> list = db.Query<Person>(sql); 16 17 //Dapper应对SQL注入 18 //where后边限定属性LastName的必须是@LastName格式,且Query中添加匿名对象new { LastName = lastName},lastName在这里传入 19 string sql = $"SELECT * FROM Person WHERE LastName=@LastName"; 20 IEnumerable<Person> list = db.Query<Person>(sql, new { LastName = lastName}); 21 return list.ToList(); 22 } 23 //using语句块结束后自动释放资源,释放数据库连接。 24 } 25 26 /// <summary> 27 /// 写入一条用户数据 28 /// </summary> 29 /// <param name="person">用户信息实体</param> 30 /// <returns></returns> 31 public bool Insert(Person person) 32 { 33 using (IDbConnection db = new SqlConnection(DbHelper.ConnectionString)) 34 { 35 string sql = "INSERT INTO Person(FirstName, LastName, EmailAddress, CreatedOn) VALUES(@FirstName, @LastName, @EmailAddress, @CreatedOn)"; 36 int result = db.Execute(sql, person); 37 return result > 0; //简化的转换写法 38 } 39 } 40 41 /// <summary> 42 /// 删除一条用户数据 43 /// </summary> 44 /// <param name="personId">用户Id</param> 45 /// <returns></returns> 46 public bool Delete(int personId) 47 { 48 using (IDbConnection db = new SqlConnection(DbHelper.ConnectionString)) 49 { 50 string sql = "DELETE FROM Person WHERE Id = @Id"; //where很重要!!! 51 int result = db.Execute(sql, new { Id = personId }); 52 return result > 0; //简化的转换写法 53 } 54 } 55 56 /// <summary> 57 /// 更新一条用户数据 58 /// </summary> 59 /// <param name="person">用户信息实体</param> 60 /// <returns></returns> 61 public bool Update(Person person) 62 { 63 using (IDbConnection db = new SqlConnection(DbHelper.ConnectionString)) 64 { 65 string sql = 66 "UPDATE Person SET FirstName = @FirstName, LastName = @LastName, EmailAddress = @EmailAddress WHERE Id = @Id"; //where很重要!!! 67 int result = db.Execute(sql, person); 68 return result > 0; //简化的转换写法 69 } 70 } 71 72 /// <summary> 73 /// 根据用户Id查询用户 74 /// </summary> 75 /// <param name="personId">用户Id</param> 76 /// <returns></returns> 77 public Person FindByPersonId(int personId) 78 { 79 using (IDbConnection db = new SqlConnection(DbHelper.ConnectionString)) 80 { 81 string sql = $"SELECT * FROM Person WHERE Id=@Id"; 82 IEnumerable<Person> list = db.Query<Person>(sql, new { Id = personId }); 83 return list.FirstOrDefault(); 84 } 85 } 86 }
五、Dashboard界面
作用:分别实现增删改查方法。
后台代码中结合具体数据,调用PersonService中的访问数据库的方法,实现相关业务功能。
1 private void btnSearch_Click(object sender, EventArgs e) 2 { 3 PersonService ps = new PersonService(); 4 List<Person> result = ps.FindListByLastName(txtSearchLastName.Text); 5 lstSearchResult.DataSource = result; 6 lstSearchResult.DisplayMember = "Display"; 7 } 8 9 private void btnCreate_Click(object sender, EventArgs e) 10 { 11 PersonService ps = new PersonService(); 12 Person person = new Person() 13 { 14 FirstName = txtFirstName.Text, 15 LastName = txtLastName.Text, 16 EmailAddress = txtEmailAddress.Text, 17 CreatedOn = DateTime.Now 18 }; 19 20 var success = ps.Insert(person); 21 MessageBox.Show(success ? "操作成功" : "操作失败"); 22 } 23 24 private void btnDelete_Click(object sender, EventArgs e) 25 { 26 PersonService ps = new PersonService(); 27 int personId = Convert.ToInt32(txtIndexPersonId.Text); 28 var success = ps.Delete(personId); 29 MessageBox.Show(success ? "操作成功" : "操作失败"); 30 } 31 32 private void btnUpdate_Click(object sender, EventArgs e) 33 { 34 PersonService ps = new PersonService(); 35 Person person = new Person() 36 { 37 Id = Convert.ToInt32(txtIndexPersonId.Text), 38 FirstName = txtFirstName.Text, 39 LastName = txtLastName.Text, 40 EmailAddress = txtEmailAddress.Text, 41 CreatedOn = DateTime.Now 42 }; 43 44 var success = ps.Update(person); 45 MessageBox.Show(success ? "操作成功" : "操作失败"); 46 } 47 48 private void btnIndex_Click(object sender, EventArgs e) 49 { 50 PersonService ps = new PersonService(); 51 int personId = Convert.ToInt32(txtIndexPersonId.Text); 52 var person = ps.FindByPersonId(personId); 53 54 txtFirstName.Text = person.FirstName; 55 txtLastName.Text = person.LastName; 56 txtEmailAddress.Text = person.EmailAddress; 57 }
前台界面如图:
六、拓展TODO
可以不使用SQL语句,但要使用Dapper的扩展工具。
使用Dapper连接MySQL数据库
要另外使用MySql.Data库
数据库连接字符串格式为
使用Dapper连接SQLite数据库
要另外使用System.Data.SQLite库
对应的DEMO程序名:
通过IP地址连接远程共享文件夹中的SQLite数据库时,调试遇到的两个问题:
1.远程IP地址解析为C盘的地址,例如"\192.168.1.10MES est.db"解析为:"C:192.168.1.10MES est.db"
解决方法:字符串格式问题,应写为@"\192.168.1.10MES est.db"
2.能够访问到远程共享文件夹后,可以新建数据库,但_dbConnection.Open();打开数据库时报错:unable to open database file
解决方法:首先尝试将远程文件夹的权限设为EveryOne拥有全部权限,未能解决;
然后尝试_dbConnection = new SQLiteConnection($"Data Source={dbFilePath};Version=3;", true); 设置parseViaFramework参数为true,问题解决。
parseViaFramework:Non-zero to parse the connection string using the built-in (i.e. framework provided) parser when opening the connection.非零,以在打开连接时使用内置(即提供的框架)解析器解析连接字符串。
七、参考