Dapper是一个轻量级的ORM工具:ORM框架的核心思想是对象关系映射,ORM是将表与表之间的操作,映射成对象和对象之间的操作,就是通过操作实体类来达到操作表的目的。从数据库提取的数据会自动按你设置的映射要求封装成特定的对象。之后你就可以通过对对象进行操作来修改数据库中的数据。这时候你面对的不是信息的碎片,而是一个形象鲜明的对象。
ORM 框架很多: Dapper、 Mybatis.Net、EntityFramework 和 NHibernate。如果你在小的项目中,使用Entity Framework、NHibernate 来处理大数据访问及关系映射,未免有点杀鸡用牛刀。而Mybatis.Net需要配置XML文件,综合考虑你会觉得觉得ORM省时省力。
流程一:
通过NuGet程序包进行Dapper安装引用: 这个引用的Dapper DLL文件是对前面说的SqlMapper.cs 源文件的封装。
流程二:
- 我们这里用Mysql数据库,那么用到的MySql.Data.dll在官网下载.net驱动包(已经附加在此教程demo中)
mysql .net连接驱动下载地址:http://dev.mysql.com/downloads/connector/net/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
CREATE TABLE person ( idint(11) NOT NULL AUTO_INCREMENT, usernamevarchar(255) NOT NULL, passwordvarchar(20) NOT NULL, ageint(11) DEFAULT NULL, registerDatedatetime DEFAULT NULL, addressvarchar(255) DEFAULT NULL, PRIMARY KEY (id) ); //Person类 publicclassPerson { publicint id { get; set; } publicstring username { get; set; } publicstring password { get; set; } publicint age { get; set; } publicDateTimeregisterDate { get; set; } publicstring address { set; get; } } |
1 2 3 4 |
public static string ConnString = "server=localhost;port=3306;user id=root;password=123456;database=test"; //SQL Server public static string ConnString = "server=localhost;user id=sa;password=123456;database=Dormitory"; |
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 |
public static int Execute(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, int? commandTimeout = null, CommandType? commandType = null); //新增 var conn = MySqlDBHelper.CreateMySqlConnection(); try { var result = conn.Execute("Insert into Person(username,password,age,registerDate,address) values (@username,@password,@age,@registerDate,@address)", new { username = txtUserName.Text, password = txtPassword.Text, age = numAge.Value, registerDate = dptRegisterDate.Value, address = txtAddress.Text }); if (result > 0) { MessageBox.Show("添加成功!"); LoadDBInfoToDgvFirst(); } } catch (Exception ex) { throw ex; } finally { if (conn.State == System.Data.ConnectionState.Open) { conn.Close(); } } |
批量新增 和新增一条语句是一样的,后面的param 是object 对象,单个模型数据和集合都可以支持。执行上面方法会插入多条记录,这样sql可以灵活的控制,参数不用像ADO.Net那样声明每个参数,最后还要把参数集合赋值给ADO的命令。可以看出这样简洁多了。
1 2 3 |
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null); 实际运用: var result = conn.Query<Person>("select * from Person order by id desc limit @indx", new { indx = num }); |
1 2 3 4 5 6 7 8 |
var param = new DynamicParameters(); param.Add("@idIn", numUpdateId.Value, DbType.Int32, ParameterDirection.Input); param.Add("@Inusername", txtUserName.Text, DbType.String, ParameterDirection.Input); param.Add("@res", 0, DbType.Int32, ParameterDirection.Output); var res2 = conn.Execute("prUpdatePersion", param, null, null, CommandType.StoredProcedure); int res = param.Get<Int32>("@res"); |
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 42 43 44 45 |
private void button4_Click(object sender, EventArgs e) { MySqlConnection mySqlConn = MySqlDBHelper.CreateMySqlConnection(); MySqlTransaction tranMySql = mySqlConn.BeginTransaction(); SqlConnection SqlServerConn = SqlServerDBHelper.CreateSqlServerConnection(); SqlTransaction tranSqlServer = SqlServerConn.BeginTransaction(); try { var persion = new Person { username = txtUserName.Text, password = txtPassword.Text, age = numAge.Value, registerDate = dptRegisterDate.Value, address = txtAddress.Text }; int result = mySqlConn.Execute("Insert into Person(username,password,age,registerDate,address) values (@username,@password,@age,@registerDate,@address)", persion, tranMySql); persion.username += "Sqlserver"; result = SqlServerConn.Execute("Insert into Person(username,password,age,registerDate,address) values (@username,@password,@age,@registerDate,@address)", persion, tranSqlServer); MessageBox.Show("添加成功!"); tranMySql.Commit(); tranSqlServer.Commit(); } catch (Exception ex) { tranMySql.Rollback(); tranSqlServer.Rollback(); throw ex; } finally { if (mySqlConn.State == System.Data.ConnectionState.Open) { mySqlConn.Close(); } if (SqlServerConn.State == System.Data.ConnectionState.Open) { SqlServerConn.Close(); } tranSqlServer.Dispose(); tranMySql.Dispose(); } tabControl.SelectedTab = tabPage2; //加载信息 LoadDBInfoToDoubleDgvFirst(); } |
通过上面的代码演示主要常用的是:封装后 Query 方法、Excute 方法。(其底层的封装的方法可以见源码:513
from:https://blog.csdn.net/laokang426/article/details/77885137