C# 使用 Dapper 实现 SQLite 增删改查
Dapper 是一款非常不错的轻型 ORM 框架,使用起来非常方便,经常使用 EF 框架的人几乎感觉不到差别,下面是自己写的 Sqlite 通用帮助类;
数据连接类;
public class SQLiteBaseRepository
{
public static string DbFile
{
get {
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VideoInfo.db");
}
}
public static SQLiteConnection SimpleDbConnection()
{ string connString = string.Format("Data Source={0};Password=******;", DbFile);
return new SQLiteConnection(connString);
}
}
数据库访问帮助类
public class SQLiteDbHelper : IDisposable
{
/// <summary>
/// 常量;
/// </summary>
const string INSERT_TABLE_ITEM_VALUE = "insert into {0} ({1}) values ({2})";
const string DELETE_TABLE_WHERE = "delete from {0} where {1}";
const string UPDATE_TABLE_EDITITEM = "update {0} set {1}";
const string UPDATE_TABLE_EDITITEM_WHERE = "update {0} set {1} where {2}";
const string Query_ITEM_TABLE_WHERE = "select {0} from {1} where {2}"; private SQLiteConnection conn; public SQLiteDbHelper()
{
conn = openDataConnection();
}
/// <summary>
/// 打开数据库链接;
/// </summary>
/// <returns></returns>
private SQLiteConnection openDataConnection()
{
var conn = SqLiteBaseRepository.SimpleDbConnection();
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
return conn;
}
/// <summary>
/// 1.1 新增实体;
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="model">实体</param>
/// <param name="autoPrimaryKey">自增主键名称</param>
/// <returns></returns>
public int Add<T>(T model, string autoPrimaryKey = "id")
{
var insertSql = GetInsertSql<T>(model,autoPrimaryKey);
return conn.Execute(insertSql);
}
/// <summary>
/// 批量新增
/// </summary>
/// <typeparam name="T">实休类</typeparam>
/// <param name="addData">实体数据列表</param>
/// <param name="autoPrimaryKey">自增主键名称</param>
/// <returns></returns>
public int Adds<T>(List<T> models, string autoPrimaryKey = "id")
{
var type = typeof(T);
int resultN = ;
var transaction = conn.BeginTransaction();
try
{
models.ForEach(d =>
{
var insertSql = GetInsertSql<T>(d);
resultN += conn.Execute(insertSql);
});
transaction.Commit();
}
catch (Exception)
{
resultN = ;
transaction.Rollback();
}
return resultN;
}
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="where">删除条件</param>
/// <returns></returns>
public int Delete<T>(string where)
{
var type = typeof(T);
string sqlStr = string.Format(DELETE_TABLE_WHERE, type.Name, where);
return conn.Execute(sqlStr);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="tableName"></param>
/// <param name="where"></param>
/// <returns></returns>
public int Delete(string tableName, string where)
{
string sqlStr = string.Format(DELETE_TABLE_WHERE,tableName,where);
return conn.Execute(sqlStr);
}
/// <summary>
/// 修改;
/// </summary>
/// <typeparam name="T">实体 Type </typeparam>
/// <param name="model">实体</param>
/// <param name="where">修改条件</param>
/// <param name="attrs">要修改的实休属性数组</param>
/// <returns></returns>
public int Edit<T>(T model, string where, params string[] attrs)
{
var sqlStr = GetUpdateSql<T>(model, where, attrs);
return conn.Execute(sqlStr);
} /// <summary>
/// 根据条件查询单一实体;
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="where">查询条件;</param>
/// <param name="attrs">要查询的字段(传入 * 为查询所有字段。)</param>
/// <returns></returns>
public T QeryByWhere<T>(string where,params string[] attrs)
{
Type type = typeof(T);
string item = attrs.Length == && attrs[] == "*" ? "*" : string.Join(",", attrs);
var sqlStr = string.Format(Query_ITEM_TABLE_WHERE, item, type.Name, where);
return conn.Query<T>(sqlStr).FirstOrDefault();
} /// <summary>
/// 根据条件查询符合条件的所有实体;
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="where"></param>
/// <returns></returns>
public List<T> QueryMultiByWhere<T>(string where)
{
Type type = typeof(T);
var sqlStr = string.Format(Query_ITEM_TABLE_WHERE, "*", type.Name, where);
return conn.Query<T>(sqlStr).ToList();
} /// <summary>
/// 生成新增 sql 语句;
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="autoPrimaryKey"></param>
/// <returns></returns>
private string GetInsertSql<T>(T model, string autoPrimaryKey = "id")
{
Type t = typeof(T);
var propertyInfo = t.GetProperties();
var proDic = propertyInfo.Where(s => !s.Name.Equals(autoPrimaryKey, StringComparison.InvariantCultureIgnoreCase))
.Select(s => new
{
key = s.Name,
value = GetValue<T>(s, model)
})
.ToDictionary(s => s.key, s => s.value);
proDic = proDic.Where(s => s.Value != "''").ToDictionary(s => s.Key, s => s.Value);
var items = string.Join(",", proDic.Keys);
var values = string.Join(",", proDic.Values);
return string.Format(INSERT_TABLE_ITEM_VALUE,t.Name,items,values);
} /// <summary>
/// 获取属性值;
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="info">字段属性信息</param>
/// <param name="model">实体</param>
/// <returns></returns>
private string GetValue<T>(PropertyInfo info,T model)
{
Type type = info.PropertyType;
var tempStr = string.Empty;
if (type == typeof(string))
{
tempStr = string.Format("'{0}'",info.GetValue(model));
return tempStr;
}
if (type == typeof(DateTime))
{
tempStr = string.Format("'{0}'", ((DateTime)info.GetValue(model)).ToString("s"));
return tempStr;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var types = type.GetGenericArguments();
if (types[] == typeof(DateTime))
{
tempStr = string.Format("'{0}'", ((DateTime)info.GetValue(model)).ToString("s"));
}
tempStr = string.Format("'{0}'",info.GetValue(model));
return tempStr;
}
tempStr = info.GetValue(model).ToString();
return tempStr;
} /// <summary>
/// 生成更新 sql 语句;
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <param name="pro"></param>
/// <param name="attrs"></param>
/// <returns></returns>
private string GetUpdateSql<T>(T model,string where, params string[] attrs)
{
Type t = typeof(T);
var propertyInfo = t.GetProperties();
var updateInfo = propertyInfo
.Where(s => attrs.Contains(s.Name))
.Select(s =>
{
if (s.PropertyType == typeof(string))
{
return string.Format("{0}='{1}'",s.Name,s.GetValue(model));
}
if (s.PropertyType == typeof(DateTime))
{
return string.Format("{0}='{1}'",s.Name,((DateTime)s.GetValue(model)).ToString("s"));
}
if (s.PropertyType.IsGenericType && s.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type[] types = s.PropertyType.GetGenericArguments();
if (types[] == typeof(DateTime))
{
return string.Format("{0}='{1}'", s.Name, ((DateTime)s.GetValue(model)).ToString("s"));
}
return string.Format("{0}={1}", s.Name, s.GetValue(model));
}
return string.Format("{0}={1}", s.Name, s.GetValue(model));
})
.ToArray();
var setStr = string.Join(",",updateInfo);
var sqlStr = string.Format(UPDATE_TABLE_EDITITEM_WHERE, t.Name, setStr, where);
return sqlStr;
}
/// <summary>
/// 释放数据连接;
/// </summary>
public void Dispose()
{
conn.Close();
conn.Dispose();
} }
https://www.cnblogs.com/llsfast/p/7883357.html
C# 使用 Dapper 实现 SQLite 增删改查的更多相关文章
- android 入门 006(sqlite增删改查)
android 入门 006(sqlite增删改查) package cn.rfvip.feb_14_2_sqlite; import android.content.Context; import ...
- iOS sqlite 增删改查 简单封装(基于 FMDB)
/** * 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * * 基于 FMDB * * 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...
- C#Sqlite增删改查
说到使用数据库的话,无非也就是对数据的增加,删除和修改以及查询.前文已经 创建好了程序,现在我们就可以来具体实现Sqlite的数据操作,增删改查. 第一步,创建连接字符串来连接数据库: private ...
- iOS SQLite 增删改查的封装(关系型)
在工程里导入libsqlite3.tbd库(Xcode 7) #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder &l ...
- C# Dapper 基本使用 增删改查事务等
using DapperTest.Models; using System.Collections.Generic; using System.Web.Http; using Dapper; usin ...
- C# Dapper 基本使用 增删改查事务
来源:https://blog.csdn.net/Tomato2313/article/details/78880969 using DapperTest.Models; using System.C ...
- sqlite 增删改查
PersonDao1.java package mm.shandong.com.testsqlsqllite.dao; import android.content.Context; import a ...
- 回家前的挣扎——SQLite增删改查
引言 最后一天,公司就两个人,也不知道弄点什么,就在网上找了Sqlite的文档,看了看,这里也是现学现卖,给自己找点事做,感觉时间过得还是比较快的,不然焦急等待,滋味不好受啊. SQLite简介 SQ ...
- iOS SQLite增删改查(简单应用)
// 注意: 在工程里导入libsqlite3.tbd库(Xcode7,如果Xcode7以下的版本则导入libsqlite3.dylib). #import <UIKit/UIKit.h> ...
随机推荐
- MySQL将某个数据库下的所有表的存储引擎修改为InnoDB类型语句
如何将mysql数据库中的MyISAM类型表更改为InnoDB类型的表 改单个表 ALTER TABLE TABLENAME ENGINE=InnoDB; ALTER TABLE TABLENAME ...
- 1211 BBS后台管理文章添加
目录 昨日内容回顾 侧边栏inclusion_tag inclusion_tag的响应 使用 自定义inclusion_tag,标签,过滤器 文章的点赞点踩 前端 后端 校验规则 文章的评论功能 1. ...
- 结构型模式(三) 装饰模式(Decorator)
一.动机(Motivate) 在房子装修的过程中,各种功能可以相互组合,来增加房子的功用.类似的,如果我们在软件系统中,要给某个类型或者对象增加功能,如果使用"继承"的方案来写代码 ...
- Post Office Problem
Description There are n houses on a line. Given an array A and A[i] represents the position of i-th ...
- pwn第一周
源码 #include <stdio.h> #include <stdlib.h> #include <unistd.h> void setbufs() { set ...
- SP1825 【FTOUR2 - Free tour II】
# \(SP1825\) 看到没有人用老师的办法,于是自己写一下思路 思路第一步:排除旧方法 首先这道题和\(4178\)不一样,因为那道题是计数,而这道题是求最值,最值有个坏处,就是对于来自相同子树 ...
- C++ error C2015: too many characters in constant
错误原因:字符常量中的字符太多了. 错误分析: 单引号表示字符型常量. 一般的,单引号中必须有,也只能有一个字符(使用转义符时,转义符所表示的字符当作一个字符看待),如果单引号中的字符数多于4个,就会 ...
- 2-SAT 知识小结
2-SAT 问题: 有 n 个变量,每一个变量都是 bool 类型的,除了这 n 个变量以外,我们还有 m 个关系表达式,关系表达式差不多是这样的: x1 & x2 = false(注意每个表 ...
- Pytest权威教程08-使用tmp目录和文件
目录 使用tmp目录和文件 tmp_path Fixture方法 tmp_path_factory Fixture方法 tmpdir Fixture方法 tmpdir_factory Fixture方 ...
- Android中相对布局的两个控件
<Button android:id="@+id/button3" android:layout_width="wrap_content" android ...