标签:work inter 方便 cat 部分 space win 教程 move
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
---
◇轻量级
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功能了吧?
1.http://hemrj.cn/System.Data.SQLite.dll
2.http://hemrj.cn/SQLite.Interop.dll.zip
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
{
/// <summary>
/// SQLite数据库操作帮助类
/// 提供一系列方便的调用:
/// Execute,Save,Update,Delete...
/// @author Nine
/// </summary>
public class SqlLiteHepler
{
private bool _showSql = true;
/// <summary>
/// 是否输出生成的SQL语句
/// </summary>
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;
}
/// <summary>
/// <para>打开SQLiteManager使用的数据库连接</para>
/// </summary>
public void Open()
{
this._conn = OpenConnection(this._dataFile);
}
public void Close()
{
if (this._conn != null)
{
this._conn.Close();
}
}
/// <summary>
/// <para>安静地关闭连接,保存不抛出任何异常</para>
/// </summary>
public void CloseQuietly()
{
if (this._conn != null)
{
try
{
this._conn.Close();
}
catch { }
}
}
/// <summary>
/// <para>创建一个连接到指定数据文件的SQLiteConnection,并Open</para>
/// <para>如果文件不存在,创建之</para>
/// </summary>
/// <param name="dataFile"></param>
/// <returns></returns>
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;
}
/// <summary>
/// <para>读取或设置SQLiteManager使用的数据库连接</para>
/// </summary>
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;
}
/// <summary>
/// <para>判断表table是否存在</para>
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
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;
}
/// <summary>
/// <para>执行SQL,返回受影响的行数</para>
/// <para>可用于执行表创建语句</para>
/// <para>paramArr == null 表示无参数</para>
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
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;
}
/// <summary>
/// <para>执行SQL,返回SQLiteDataReader</para>
/// <para>返回的Reader为原始状态,须自行调用Read()方法</para>
/// <para>paramArr=null,则表示无参数</para>
/// </summary>
/// <param name="sql"></param>
/// <param name="paramArr"></param>
/// <returns></returns>
public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] paramArr)
{
return (SQLiteDataReader)ExecuteReader(sql, paramArr, (ReaderWrapper)null);
}
/// <summary>
/// <para>执行SQL,如果readerWrapper!=null,那么将调用readerWrapper对SQLiteDataReader进行包装,并返回结果</para>
/// </summary>
/// <param name="sql"></param>
/// <param name="paramArr">null 表示无参数</param>
/// <param name="readerWrapper">null 直接返回SQLiteDataReader</param>
/// <returns></returns>
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;
}
/// <summary>
/// <para>执行SQL,返回结果集,使用RowWrapper对每一行进行包装</para>
/// <para>如果结果集为空,那么返回空List (List.Count=0)</para>
/// <para>rowWrapper = null时,使用WrapRowToDictionary</para>
/// </summary>
/// <param name="sql"></param>
/// <param name="paramArr"></param>
/// <param name="rowWrapper"></param>
/// <returns></returns>
public List<object> 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<object> result = new List<object>();
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<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < fc; i++)
{
string fieldName = reader.GetName(i);
object value = reader.GetValue(i);
row.Add(fieldName, value);
}
return row;
}
/// <summary>
/// <para>执行insert into语句</para>
/// </summary>
/// <param name="table"></param>
/// <param name="entity"></param>
/// <returns></returns>
public int Save(string table, Dictionary<string, object> 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<string, object> entity)
{
List<SQLiteParameter> list = new List<SQLiteParameter>();
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<string, object> 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<string, object> 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();
}
/// <summary>
/// <para>执行update语句</para>
/// <para>where参数不必要包含'where'关键字</para>
///
/// <para>如果where=null,那么忽略whereParams</para>
/// <para>如果where!=null,whereParams=null,where部分无参数</para>
/// </summary>
/// <param name="table"></param>
/// <param name="entity"></param>
/// <param name="where"></param>
/// <param name="whereParams"></param>
/// <returns></returns>
public int Update(string table, Dictionary<string, object> 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);
}
/// <summary>
/// <para>查询一行记录,无结果时返回null</para>
/// <para>conditionCol = null时将忽略条件,直接执行select * from table </para>
/// </summary>
/// <param name="table"></param>
/// <param name="conditionCol"></param>
/// <param name="conditionVal"></param>
/// <returns></returns>
public Dictionary<string, object> 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<object> list = this.ExecuteRow(sql, new SQLiteParameter[] {
new SQLiteParameter(conditionCol,conditionVal)
}, null);
if (list.Count == 0)
return null;
return (Dictionary<string, object>)list[0];
}
/// <summary>
/// 执行delete from table 语句
/// where不必包含'where'关键字
/// where=null时将忽略whereParams
/// </summary>
/// <param name="table"></param>
/// <param name="where"></param>
/// <param name="whereParams"></param>
/// <returns></returns>
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
/// <summary>
/// 执行一个查询语句,返回一个包含查询结果的DataTable
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 创建SQLite数据库文件
/// </summary>
/// <param name="dbPath">要创建的SQLite数据库文件路径</param>
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();
}
}
}
/// <summary>
/// 对SQLite数据库执行增删改操作,返回受影响的行数。
/// </summary>
/// <param name="sql">要执行的增删改的SQL语句</param>
/// <param name="parameters">执行增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>
/// <returns></returns>
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;
}
/// <summary>
/// 执行一个查询语句,返回一个关联的SQLiteDataReader实例
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>
/// <returns></returns>
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);
}
/// <summary>
/// 执行一个查询语句,返回查询结果的第一行第一列
/// </summary>
/// <param name="sql">要执行的查询语句</param>
/// <param name="parameters">执行SQL查询语句所需要的参数,参数必须以它们在SQL语句中的顺序为准</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 查询数据库中的所有数据类型信息
/// </summary>
/// <returns></returns>
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
}
/// <summary>
/// 在SQLiteManager.Execute方法中回调,将SQLiteDataReader包装成object
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public delegate object ReaderWrapper(SQLiteDataReader reader);
/// <summary>
/// 将SQLiteDataReader的行包装成object
/// </summary>
/// <param name="rowNum"></param>
/// <param name="reader"></param>
/// <returns></returns>
public delegate object RowWrapper(int rowNum, SQLiteDataReader reader);
}
using System;
using System.Data.SQLite;
using System.Windows;
namespace SqlLiteHelper
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
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
标签:work inter 方便 cat 部分 space win 教程 move
原文地址:https://www.cnblogs.com/Jamnine/p/12161963.html