Dapper.net 的简单应用
配置操作
Web.config配置
<appSettings>
//注:本人使用mysql
<add key="strconn" value="server=localhost;user id=***;password=***;database=数据库;Allow User Variables=True" />
appSettings>
语法操作
基础语法封装
using Dapper;
using MyModel;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
namespace MyDAL
{
public class SqlConfig
{
public readonly static string sqlconnct = System.Configuration.ConfigurationManager.AppSettings["strconn"];
public MySqlConnection conn = null;
public SqlConfig()
{
conn = new MySqlConnection(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();
}
}
public IEnumerable GetInfoList(string sql, object parameter = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
try
{
OpenConnect();
IEnumerable result = conn.Query(sql, parameter, transaction, buffered, commandTimeout, commandType);
CloseConnect();
return result;
}
catch (Exception ex)
{
throw ex;
}
}
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;
}
}
public int GetInfoCounts(string sql, object parameter = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
try
{
OpenConnect();
int result = conn.Query<int>(sql, parameter, transaction, buffered, commandTimeout, commandType).First() ;
CloseConnect();
return result;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
示例操作
查询结果示例
string sqlList="select * from table";
List<T> list = SqlConfig对象实例.GetInfoList(sqlList)<T>.ToList();
查询数量示例
string sqlCount = string.Format("select count(*) as rows from {0} ", table)
int counts = SqlConfig对象实例.GetInfoCounts(sqlCount);
插入更新删除
string sql = "insert into userinfo(Name,Password,Phone,Address,Status) values(@Name,@Password,@Phone,@Address,@Status)";
bool result = SqlConfig对象实例.UpdateSql(sql,user);
string sql = "update userinfo set name=@Name,password=@Password,phone=@Phone,address=@Address,status=@Status where id=@ID";
bool result = SqlConfig对象实例.UpdateSql(sql,user);
string sql = string.Format("delete from userinfo where id in ({0})",ids);
bool result = SqlConfig对象实例.UpdateSql(sql);
下一章介绍:
自己构建的项目框架使用的 easyui+.net mvc +Autofac+dapper.net 的分页操作