首先需要添加 NuGet 包 Dapper 以及引用Configuration
<connectionStrings>
<add name="SqlSrc" connectionString="Data Source=.;Initial Catalog=Demo;Integrated Security=True"/> </connectionStrings>
using Dapper;using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ModelServer{ public class DBDapper { //获取连接字符串 public readonly static string sqlconnct = System.Configuration.ConfigurationManager.ConnectionStrings["SqlSrc"].ConnectionString; //初始化连接对象 public SqlConnection conn = null; public DBDapper() { conn = new SqlConnection(sqlconnct); } ////// 打开数据库连接 /// private void OpenConnect() { if (conn.State == ConnectionState.Closed) { try { conn.Open(); } catch (Exception e) { throw e; } } } ////// 关闭数据库连接 /// private void CloseConnect() { if (conn.State == ConnectionState.Open) { conn.Close(); } } ////// 查询语句,必要形参sql语句或存储过程名称,后面参数用于扩展可以不写,若两边有参数中间用null占位 /// ///强类型的类 /// sql执行语句或存储过程名称 /// sql参数,可匿名类型,可对象类型 /// 执行事务 /// /// /// ///对象集合 public IEnumerableGetInfoList (string sql, object parameter = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?)) { try { OpenConnect(); //可以让结果转换成其他集合形式 例:list、array等集合,方法: ToList<>、ToArray<> IEnumerable result = conn.Query (sql, parameter, transaction, buffered, commandTimeout, commandType); CloseConnect(); return result; } catch (Exception ex) { throw ex; } } /// /// 插入、更新或删除语句,必要形参sql语句或存储过程名称,后面参数用于扩展可以不写,若两边有参数中间用null占位 /// ///强类型的类 /// sql执行语句或存储过程名称 /// sql参数,可匿名类型,可对象类型 /// 执行事务 /// /// ///成功:true;失败:false public bool UpdateSql(string sql, object parameter = null, IDbTransaction transaction = null, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?)) { try { OpenConnect(); int result = conn.Execute(sql, parameter, transaction, commandTimeout, commandType); CloseConnect(); if (result > 0) { return true; } else { return false; } } catch (Exception ex) { throw ex; } } ////// 根据条件获取数据库表中列表数量,必要形参sql,后面参数用于扩展可以不写,若两边有参数中间用null占位 /// /// sql执行语句或存储过程名称 /// sql参数,可匿名类型,可对象类型 /// /// /// /// ///public int GetInfoCounts(string sql, object parameter = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?)) { try { OpenConnect(); //注意:sql语句应该是这种形式 select count(*) as rows from table int result = conn.Query (sql, parameter, transaction, buffered, commandTimeout, commandType).First(); CloseConnect(); return result; } catch (Exception ex) { throw ex; } } } }