C# 使用 Dapper 实现 SQLite 增删改查

Dapper 是一款非常不错的轻型 ORM 框架,使用起来非常方便,经常使用 EF 框架的人几乎感觉不到差别,下面是自己写的 Sqlite 通用帮助类;

1> 数据连接类;

    public class SQLiteBaseRepository
    {
        public static string DbFile
        {
            get {
                return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VideoInfo.db");
            }
        }
        public static SQLiteConnection SimpleDbConnection()
        {
            string connString = "Data Source=" + DbFile + ";Pooling=True;Max Pool Size=10;FailIfMissing=True;Journal Mode=Off;Synchronous = OFF";
            return new SQLiteConnection(connString);
        }
    }

2> 数据库访问帮助类

    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 = 0;
            var transaction = conn.BeginTransaction();
            try
            {
                models.ForEach(d =>
                {
                    var insertSql = GetInsertSql<T>(d);
                    resultN += conn.Execute(insertSql);
                });
                transaction.Commit();
            }
            catch (Exception)
            {
                resultN = 0;
                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 == 1 && attrs[0] == "*" ? "*" : 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[0] == 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[0] == 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();
        }

    }
时间: 2024-10-06 00:16:20

C# 使用 Dapper 实现 SQLite 增删改查的相关文章

iOS sqlite 增删改查 简单封装(基于 FMDB)

/** *  对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * *  基于 FMDB * *  操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整体进行操作 * *  根据 model 对象自动建表,字段类型只支持 NSString , NSIteger , float * *  用到 runtime 运行时获取 model 属性 * */ 1 // 2 // AGDatabaseManager.h 3 // 4 // Created by

android 入门 006(sqlite增删改查)

package cn.rfvip.feb_14_2_sqlite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class MyOpenHelper e

iOS SQLite 增删改查的封装(关系型)

在工程里导入libsqlite3.tbd库(Xcode 7) #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end #import "AppDelegate.h" #import "RootViewController.h"

SQLite增删改查

package com.scme.db; import java.util.ArrayList; import java.util.List; import com.scme.bean.Students; import com.scme.bean.Tongxunlu; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; impo

iOS SQLite增删改查(简单应用)

// 注意: 在工程里导入libsqlite3.tbd库(Xcode7,如果Xcode7以下的版本则导入libsqlite3.dylib). #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end #import "AppDelegate.h"

sqlite 增删改查

PersonDao1.java package mm.shandong.com.testsqlsqllite.dao; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import mm.shandong.com.tests

Dapper进行增删改查 z

http://www.cnblogs.com/huangkaiyan10/p/4640548.html 项目背景 前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET.微软的EF.NH等.再跟经理讨论后,经理强调不要用 Ef,NH做ORM,后期的sql优化不好做,公司也没有人对EF,Nh 等orm优化比较熟悉的.强调说的,我们的项目要做的得简单,可以使用ADO.NET 写原始的sql.但我自己还是喜欢ORM的,它可以提高数据访问层的开发.有一天,在订阅张善友 d

使用轻量级ORM Dapper进行增删改查

  项目背景 前一段时间,开始做一个项目,在考虑数据访问层是考虑技术选型,考虑过原始的ADO.NET.微软的EF.NH等.再跟经理讨论后,经理强调不要用Ef,NH做ORM,后期的sql优化不好做,公司也没有人对EF,Nh 等orm优化比较熟悉的.强调说的,我们的项目要做的得简单,可以使用ADO.NET 写原始的sql.但我自己还是喜欢ORM的,它可以提高数据访问层的开发.有一天,在订阅张善友 doNet跨平台微信公众号里,看到Dapper的推荐.了解之后,我自己喜欢喜欢Dapper,可以满足我这

【Android】Sqlite数据库增删改查

Android系统内置一个Sqlite数据库,如果app需要使用Sqlite数据库数据库存储数据,Android会为此app生成一个.db文件.这个数据库在data/data/<package_name>/databases里面,其中<package_name>为该安卓app的工程包名,这个目录必须root后才能看到.在Windows,单机的应用程序,存储数据,基本放到一个文件里面,正如游戏的存档,基本就是把当前的游戏状态存到一个用户很难找到的文件里面.每次存档读档就是一个从这个存