连接对象
using Simple.Data;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Simple.Data.Mysql;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
namespace histest.Tools
{
public class DataBaseHelper
{
private static readonly string ConnectionSqlserver = ConfigurationManager.ConnectionStrings["dbsqlserver"].ConnectionString;
private static readonly string ConnectionMysql = ConfigurationManager.ConnectionStrings["dbmysql"].ConnectionString;
//dapper
public static SqlConnection DepperSqlserver()
{
SqlConnection connection = new SqlConnection(ConnectionSqlserver);
connection.Open();
return connection;
}
public static MySqlConnection DepperMysql()
{
MySqlConnection connection = new MySqlConnection(ConnectionMysql);
connection.Open();
return connection;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Dapper;
using System.Collections;
namespace histest.Tools
{
public class DapperHelper
{
public static List<T> Select<T>(string sql, Object param)
{
using (IDbConnection conn = DataBaseHelper.DepperSqlserver())
{
List<T> datas = conn.Query<T>(sql, param).ToList<T>();
return datas;
}
}
public static T Find<T>(string sql, Object param)
{
using (IDbConnection conn = DataBaseHelper.DepperSqlserver()) {
T datas = conn.Query<T>(sql, param).SingleOrDefault<T>();
return datas;
}
}
public static int Count(string sql,Object param)
{
using (IDbConnection conn = DataBaseHelper.DepperSqlserver()) {
List<dynamic> datas = conn.Query(sql, param).ToList();
return datas.ToArray().Length;
}
}
public static int Update(string sql,Object param)
{
using (IDbConnection conn = DataBaseHelper.DepperSqlserver())
{
return conn.Execute(sql,param);
}
}
public static int Add(string sql,Object param)
{
using (IDbConnection conn = DataBaseHelper.DepperSqlserver()) {
return conn.Execute(sql, param);
}
}
public static int Execute(String sql,Object param)
{
using (IDbConnection conn = DataBaseHelper.DepperSqlserver())
{
return conn.Execute(sql, param);
}
}
}
}
使用
查询一条记录 DapperHelper.Find<dynamic>("select * from where id=@id",new{id=7} );
查询多条记录 DapperHelper.Select<dynamic>("select * from where typeid=@typeid",new{typeid=5} );
查询总条数 DapperHelper.Count<dynamic>("select * from where typeid=@typeid",new{typeid=5} );
增删改 DapperHelper.Execute(sql, new{username="zhangsan",password="admin"});