SqlLite数据库帮助类和基本DEMO


title: SqlLite数据库帮助类和基本DEMO
categories: Codeing
date: 2019-10-16 15:05:13
tags: [C#,编程开发,实用教程,DEMO]
thumbnail: http://hemrj.cn/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20191010152920.jpg
---

SqlLite数据库帮助类和基本DEMO

SQLlite优点

◇轻量级
SQLite和C/S模式的数据库软件不同,它是进程内的数据库引擎,因此不存在数据库的客户端和服务器。使用SQLite一般只需要带上它的一个动态 库,就可以享受它的全部功能。而且那个动态库的尺寸也挺小,以版本3.6.11为例,Windows下487KB、Linux下347KB。
◇绿色软件
SQLite的另外一个特点是绿色:它的核心引擎本身不依赖第三方的软件,使用它也不需要“安装”。所以在部署的时候能够省去不少麻烦。
◇单一文件
所谓的“单一文件”,就是数据库中所有的信息(比如表、视图、触发器、等)都包含在一个文件内。这个文件可以copy到其它目录或其它机器上,也照用不误。
◇跨平台/可移植性
如果光支持主流操作系统,那就没啥好吹嘘的了。除了主流操作系统,SQLite还支持了很多冷门的操作系统。我个人比较感兴趣的是它对很多嵌入式系统(比如Android、WindowsMobile、Symbin、Palm、VxWorks等)的支持。
◇内存数据库(in-memory database)
这年头,内存越来越便宜,很多普通PC都开始以GB为单位来衡量内存(服务器就更甭提了)。这时候,SQLite的内存数据库特性就越发显得好用。
SQLite的API不区分当前操作的数据库是在内存还是在文件(对于存储介质是透明的)。所以如果你觉得磁盘I/O有可能成为瓶颈的话,可以考虑切换 为内存方式。切换的时候,操作SQLite的代码基本不用大改,只要在开始时把文件Load到内存,结束时把内存的数据库Dump回文件就OK了。在这种情况下,前面提到的“onlinebackup API”就派上用场了,聪明的同学应该明白我为啥这么期待backup功能了吧?

添加引用

管理NuGet管理程序-->浏览-->搜索System.Data.SQLite,安装引用
或者直接在此下载,下载后引用System.Data.SQLite.dll,把SQLite.Interop.dll.zip解压放在debug目录下

1.http://hemrj.cn/System.Data.SQLite.dll
2.http://hemrj.cn/SQLite.Interop.dll.zip

SqlLite帮助类

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nine.UnitlLibrary
{
    ///  
    /// SQLite数据库操作帮助类
    /// 提供一系列方便的调用:
    /// Execute,Save,Update,Delete...
    /// @author Nine
    /// 
    public class SqlLiteHepler
    {

        private bool _showSql = true;

        /// 
        /// 是否输出生成的SQL语句
        /// 
        public bool ShowSql
        {
            get
            {
                return this._showSql;
            }
            set
            {
                this._showSql = value;
            }
        }

        private readonly string _dataFile;

        private SQLiteConnection _conn;

        public SqlLiteHepler(string dataFile)
        {
            if (dataFile == null)
                throw new ArgumentNullException("dataFile=null");
            this._dataFile = dataFile;
        }

        /// 
        /// 打开SQLiteManager使用的数据库连接
        /// 
        public void Open()
        {
            this._conn = OpenConnection(this._dataFile);
        }

        public void Close()
        {
            if (this._conn != null)
            {
                this._conn.Close();
            }
        }

        /// 
        /// 安静地关闭连接,保存不抛出任何异常
        /// 
        public void CloseQuietly()
        {
            if (this._conn != null)
            {
                try
                {
                    this._conn.Close();
                }
                catch { }
            }
        }

        /// 
        /// 创建一个连接到指定数据文件的SQLiteConnection,并Open
        /// 如果文件不存在,创建之
        /// 
        /// 
        /// 
        public static SQLiteConnection OpenConnection(string dataFile)
        {
            if (dataFile == null)
                throw new ArgumentNullException("dataFile=null");

            if (!File.Exists(dataFile))
            {
                SQLiteConnection.CreateFile(dataFile);
            }

            SQLiteConnection conn = new SQLiteConnection();
            SQLiteConnectionStringBuilder conStr = new SQLiteConnectionStringBuilder
            {
                DataSource = dataFile
            };
            conn.ConnectionString = conStr.ToString();
            conn.Open();
            return conn;
        }

        /// 
        /// 读取或设置SQLiteManager使用的数据库连接
        /// 
        public SQLiteConnection Connection
        {
            get
            {
                return this._conn;
            }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException();
                }
                this._conn = value;
            }
        }

        protected void EnsureConnection()
        {
            if (this._conn == null)
            {
                throw new Exception("SQLiteManager.Connection=null");
            }
        }

        public string GetDataFile()
        {
            return this._dataFile;
        }

        /// 
        /// 判断表table是否存在
        /// 
        /// 
        /// 
        public bool TableExists(string table)
        {
            if (table == null)
                throw new ArgumentNullException("table=null");
            this.EnsureConnection();
            // SELECT count(*) FROM sqlite_master WHERE type='table' AND name='test';
            SQLiteCommand cmd = new SQLiteCommand("SELECT count(*) as c FROM sqlite_master WHERE type='table' AND name=@tableName ");
            cmd.Connection = this.Connection;
            cmd.Parameters.Add(new SQLiteParameter("tableName", table));
            SQLiteDataReader reader = cmd.ExecuteReader();
            reader.Read();
            int c = reader.GetInt32(0);
            reader.Close();
            reader.Dispose();
            cmd.Dispose();
            //return false;
            return c == 1;
        }

        /// 
        /// 执行SQL,返回受影响的行数
        /// 可用于执行表创建语句
        /// paramArr == null 表示无参数
        /// 
        /// 
        /// 
        public int ExecuteNonQuery(string sql, SQLiteParameter[] paramArr)
        {
            if (sql == null)
            {
                throw new ArgumentNullException("sql=null");
            }
            this.EnsureConnection();

            if (this.ShowSql)
            {
                Console.WriteLine("SQL: " + sql);
            }

            SQLiteCommand cmd = new SQLiteCommand();
            cmd.CommandText = sql;
            if (paramArr != null)
            {
                foreach (SQLiteParameter p in paramArr)
                {
                    cmd.Parameters.Add(p);
                }
            }
            cmd.Connection = this.Connection;
            int c = cmd.ExecuteNonQuery();
            cmd.Dispose();
            return c;
        }

        /// 
        /// 执行SQL,返回SQLiteDataReader
        /// 返回的Reader为原始状态,须自行调用Read()方法
        /// paramArr=null,则表示无参数
        /// 
        /// 
        /// 
        /// 
        public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] paramArr)
        {
            return (SQLiteDataReader)ExecuteReader(sql, paramArr, (ReaderWrapper)null);
        }

        /// 
        /// 执行SQL,如果readerWrapper!=null,那么将调用readerWrapper对SQLiteDataReader进行包装,并返回结果
        /// 
        /// 
        /// null 表示无参数
        /// null 直接返回SQLiteDataReader
        /// 
        public object ExecuteReader(string sql, SQLiteParameter[] paramArr, ReaderWrapper readerWrapper)
        {
            if (sql == null)
            {
                throw new ArgumentNullException("sql=null");
            }
            this.EnsureConnection();

            SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection);
            if (paramArr != null)
            {
                foreach (SQLiteParameter p in paramArr)
                {
                    cmd.Parameters.Add(p);
                }
            }
            SQLiteDataReader reader = cmd.ExecuteReader();
            object result = null;
            if (readerWrapper != null)
            {
                result = readerWrapper(reader);
            }
            else
            {
                result = reader;
            }
            reader.Close();
            reader.Dispose();
            cmd.Dispose();
            return result;
        }

        /// 
        /// 执行SQL,返回结果集,使用RowWrapper对每一行进行包装
        /// 如果结果集为空,那么返回空List (List.Count=0)
        /// rowWrapper = null时,使用WrapRowToDictionary
        /// 
        /// 
        /// 
        /// 
        /// 
        public List ExecuteRow(string sql, SQLiteParameter[] paramArr, RowWrapper rowWrapper)
        {
            if (sql == null)
            {
                throw new ArgumentNullException("sql=null");
            }
            this.EnsureConnection();

            SQLiteCommand cmd = new SQLiteCommand(sql, this.Connection);
            if (paramArr != null)
            {
                foreach (SQLiteParameter p in paramArr)
                {
                    cmd.Parameters.Add(p);
                }
            }

            if (rowWrapper == null)
            {
                rowWrapper = new RowWrapper(SqlLiteHepler.WrapRowToDictionary);
            }

            SQLiteDataReader reader = cmd.ExecuteReader();
            List result = new List();
            if (reader.HasRows)
            {
                int rowNum = 0;
                while (reader.Read())
                {
                    object row = rowWrapper(rowNum, reader);
                    result.Add(row);
                    rowNum++;
                }
            }
            reader.Close();
            reader.Dispose();
            cmd.Dispose();
            return result;
        }

        public static object WrapRowToDictionary(int rowNum, SQLiteDataReader reader)
        {
            int fc = reader.FieldCount;
            Dictionary row = new Dictionary();
            for (int i = 0; i < fc; i++)
            {
                string fieldName = reader.GetName(i);
                object value = reader.GetValue(i);
                row.Add(fieldName, value);
            }
            return row;
        }

        /// 
        /// 执行insert into语句
        /// 
        /// 
        /// 
        /// 
        public int Save(string table, Dictionary entity)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table=null");
            }
            this.EnsureConnection();
            string sql = BuildInsert(table, entity);
            return this.ExecuteNonQuery(sql, BuildParamArray(entity));
        }

        private static SQLiteParameter[] BuildParamArray(Dictionary entity)
        {
            List list = new List();
            foreach (string key in entity.Keys)
            {
                list.Add(new SQLiteParameter(key, entity[key]));
            }
            if (list.Count == 0)
                return null;
            return list.ToArray();
        }

        private static string BuildInsert(string table, Dictionary entity)
        {
            StringBuilder buf = new StringBuilder();
            buf.Append("insert into ").Append(table);
            buf.Append(" (");
            foreach (string key in entity.Keys)
            {
                buf.Append(key).Append(",");
            }
            buf.Remove(buf.Length - 1, 1); // 移除最后一个,
            buf.Append(") ");
            buf.Append("values(");
            foreach (string key in entity.Keys)
            {
                buf.Append("@").Append(key).Append(","); // 创建一个参数
            }
            buf.Remove(buf.Length - 1, 1);
            buf.Append(") ");

            return buf.ToString();
        }

        private static string BuildUpdate(string table, Dictionary entity)
        {
            StringBuilder buf = new StringBuilder();
            buf.Append("update ").Append(table).Append(" set ");
            foreach (string key in entity.Keys)
            {
                buf.Append(key).Append("=").Append("@").Append(key).Append(",");
            }
            buf.Remove(buf.Length - 1, 1);
            buf.Append(" ");
            return buf.ToString();
        }

        /// 
        /// 执行update语句
        /// where参数不必要包含'where'关键字
        /// 
        /// 如果where=null,那么忽略whereParams
        /// 如果where!=null,whereParams=null,where部分无参数
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public int Update(string table, Dictionary entity, string where, SQLiteParameter[] whereParams)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table=null");
            }
            this.EnsureConnection();
            string sql = BuildUpdate(table, entity);
            SQLiteParameter[] arr = BuildParamArray(entity);
            if (where != null)
            {
                sql += " where " + where;
                if (whereParams != null)
                {
                    SQLiteParameter[] newArr = new SQLiteParameter[arr.Length + whereParams.Length];
                    Array.Copy(arr, newArr, arr.Length);
                    Array.Copy(whereParams, 0, newArr, arr.Length, whereParams.Length);

                    arr = newArr;
                }
            }
            return this.ExecuteNonQuery(sql, arr);
        }

        /// 
        /// 查询一行记录,无结果时返回null
        /// conditionCol = null时将忽略条件,直接执行select * from table 
        /// 
        /// 
        /// 
        /// 
        /// 
        public Dictionary QueryOne(string table, string conditionCol, object conditionVal)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table=null");
            }
            this.EnsureConnection();

            string sql = "select * from " + table;
            if (conditionCol != null)
            {
                sql += " where " + conditionCol + "=@" + conditionCol;
            }
            if (this.ShowSql)
            {
                Console.WriteLine("SQL: " + sql);
            }

            List list = this.ExecuteRow(sql, new SQLiteParameter[] {
                new SQLiteParameter(conditionCol,conditionVal)
            }, null);
            if (list.Count == 0)
                return null;
            return (Dictionary)list[0];
        }
        /// 
        /// 执行delete from table 语句
        /// where不必包含'where'关键字
        /// where=null时将忽略whereParams
        /// 
        /// 
        /// 
        /// 
        /// 
        public int Delete(string table, string where, SQLiteParameter[] whereParams)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table=null");
            }
            this.EnsureConnection();
            string sql = "delete from " + table + " ";
            if (where != null)
            {
                sql += "where " + where;
            }

            return this.ExecuteNonQuery(sql, whereParams);
        }

        #region NINE 19.10.10
        ///  
        /// 执行一个查询语句,返回一个包含查询结果的DataTable 
        ///  
        /// 要执行的查询语句 
        /// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 
        ///  
        public DataTable ExecuteDataTable(string sql, SQLiteParameter[] parameters)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, _conn))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }
                SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
                DataTable data = new DataTable();
                adapter.Fill(data);
                return data;
            }
        }
        ///  
        /// 创建SQLite数据库文件 
        ///  
        /// 要创建的SQLite数据库文件路径 
        public static void CreateDB(string dbPath)
        {
            using (SQLiteConnection connection = new SQLiteConnection("Data Source=" + dbPath))
            {
                connection.Open();
                using (SQLiteCommand command = new SQLiteCommand(connection))
                {
                    command.CommandText = "CREATE TABLE Demo(id integer NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE)";
                    command.ExecuteNonQuery();
                    command.CommandText = "DROP TABLE Demo";
                    command.ExecuteNonQuery();
                }
            }
        }
        ///  
        /// 对SQLite数据库执行增删改操作,返回受影响的行数。 
        ///  
        /// 要执行的增删改的SQL语句 
        /// 执行增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 
        ///  
        public int ExecuteNonQuerySql(string sql, SQLiteParameter[] parameters)
        {
            int affectedRows = 0;
            using (DbTransaction transaction = _conn.BeginTransaction())
            {
                using (SQLiteCommand command = new SQLiteCommand(_conn))
                {
                    command.CommandText = sql;
                    if (parameters != null)
                    {
                        command.Parameters.AddRange(parameters);
                    }
                    affectedRows = command.ExecuteNonQuery();
                }
                transaction.Commit();
            }
            return affectedRows;
        }
        ///  
        /// 执行一个查询语句,返回一个关联的SQLiteDataReader实例 
        ///  
        /// 要执行的查询语句 
        /// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 
        ///  
        public SQLiteDataReader ExecuteReaderSql(string sql, SQLiteParameter[] parameters)
        {
            SQLiteCommand command = new SQLiteCommand(sql, _conn);
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        ///  
        /// 执行一个查询语句,返回查询结果的第一行第一列 
        ///  
        /// 要执行的查询语句 
        /// 执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准 
        ///  
        public Object ExecuteScalar(string sql, SQLiteParameter[] parameters)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, _conn))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }
                SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
                DataTable data = new DataTable();
                adapter.Fill(data);
                return data;
            }
        }

        ///  
        /// 查询数据库中的所有数据类型信息 
        ///  
        ///  
        public DataTable GetSchema()
        {
            using (SQLiteConnection connection = new SQLiteConnection(_conn))
            {
                DataTable data = connection.GetSchema("TABLES");
                connection.Close();
                //foreach (DataColumn column in data.Columns) 
                //{ 
                //  Console.WriteLine(column.ColumnName); 
                //} 
                return data;
            }
        }
        #endregion
    }

    /// 
    /// 在SQLiteManager.Execute方法中回调,将SQLiteDataReader包装成object 
    /// 
    /// 
    /// 
    public delegate object ReaderWrapper(SQLiteDataReader reader);

    /// 
    /// 将SQLiteDataReader的行包装成object
    /// 
    /// 
    /// 
    /// 
    public delegate object RowWrapper(int rowNum, SQLiteDataReader reader);
} 
 

SqlLite DEMO

using System;
using System.Data.SQLite;
using System.Windows;

namespace SqlLiteHelper
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SqlLiteHepler sqlLiteHepler = new SqlLiteHepler(@"D:\NineBackstageToolsDB.db");
            sqlLiteHepler.Open();
            //insert
            string insertSql = "INSERT INTO CountUserData(JsonData) values (@JsonData)";
            SQLiteParameter[] insertParameters = new SQLiteParameter[]{
            new SQLiteParameter("@JsonData","test") };
            int insertRowCount = sqlLiteHepler.ExecuteNonQuerySql(insertSql, insertParameters);
            //update
            string updateSql = "Update CountUserData  set JsonData= @JsonData where id = @ID";
            SQLiteParameter[] updateParameters = new SQLiteParameter[]{
            new SQLiteParameter("@JsonData","update"),
            new SQLiteParameter("@ID","3")
            };
            int updateRowCount = sqlLiteHepler.ExecuteNonQuerySql(updateSql, updateParameters);
            //delete
            string deleteSql = "delete from CountUserData where id = @ID";
            SQLiteParameter[] deleteParameters = new SQLiteParameter[]{
            new SQLiteParameter("@ID","4")
            };
            int deleteRowCount = sqlLiteHepler.ExecuteNonQuerySql(deleteSql, deleteParameters);
            //select
            string sqlText = "select * from XyhisLog where (logtime) > (@logtime)";
            SQLiteParameter[] selectParameters = new SQLiteParameter[]{
            new SQLiteParameter("@logtime",DateTime.Now.Date.ToString().Replace("/","-")) };
            var ss = sqlLiteHepler.ExecuteDataTable(sqlText, selectParameters);

        }
    }
}

SqlLiteHelper Demo 源码下载 http://hemrj.cn/SqlLiteHelper.zip

你可能感兴趣的:(SqlLite数据库帮助类和基本DEMO)