目录
1、SQLite介绍
SQLite,是一款轻型的数据库,是遵守的ACID关系型数据库管理系统,它包含在一个相对小的C库中。它的设计目标嵌入式是的,而且已经在很多中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等。
2、C#下调用SQLite数据库
在NuGet程序包内,搜索System.Data.Sqlite,安装Sqlite类库
sqliteHelper中主要用到2个方法:
a、ExecuteNonQuery 执行Insert,Update、Delete、创建库等操作,返回值是数据库影响的行数
b、ExecuteDataSet执行Select操作,返回查询数据集
public class SQLiteHelper
{
public static string ConnectionString = "Data Source =" + Environment.CurrentDirectory + @"\database.db" + ";Pooling = true; FailIfMissing = true";
///
/// 执行数据库操作(新增、更新或删除)
///
/// 连接字符串
/// SqlCommand对象
/// 受影响的行数
public int ExecuteNonQuery(string cmdstr, params SQLiteParameter[] cmdParms)
{
int result = 0;
using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
{
SQLiteTransaction trans = null;
SQLiteCommand cmd = new SQLiteCommand(cmdstr);
PrepareCommand(cmd, conn, ref trans, true, cmd.CommandType, cmd.CommandText, cmdParms);
try
{
result = cmd.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
}
return result;
}
///
/// 预处理Command对象,数据库链接,事务,需要执行的对象,参数等的初始化
///
/// Command对象
/// Connection对象
/// Transcation对象
/// 是否使用事务
/// SQL字符串执行类型
/// SQL Text
/// SQLiteParameters to use in the command
private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, ref SQLiteTransaction trans, bool useTrans, CommandType cmdType, string cmdText, params SQLiteParameter[] cmdParms)
{
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (useTrans)
{
trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = trans;
}
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SQLiteParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
catch
{
}
}
///
/// 数据库查询
///
/// sql语句
/// 表名
/// DataSet对象
public DataSet ExecuteDataSet(string cmdstr)
{
DataSet ds = new DataSet();
SQLiteConnection conn = new SQLiteConnection(ConnectionString);
SQLiteTransaction trans = null;
SQLiteCommand cmd = new SQLiteCommand(cmdstr);
PrepareCommand(cmd, conn, ref trans, false, cmd.CommandType, cmd.CommandText);
try
{
SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
sda.Fill(ds);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmd.Connection != null)
{
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
}
}
return ds;
}
4、Sqlite部分技巧
a、SQLiteConnection类的CreateFile方法,在程序内动态创建数据库文件,通过下面的方法即可创建出Analysis.db名称的数据库
///
/// 数据库路径
///
private static string databasepath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
///
/// 数据库名称
///
private const string databasename = "Analysis.db";
///
/// 创建数据库
///
public static void CreateDataBase()
{
try
{
if (!File.Exists(databasepath + databasename))
{
if (!Directory.Exists(databasepath))
Directory.CreateDirectory(databasepath);
SQLiteConnection.CreateFile(databasepath + databasename);
LogHelper.Info("创建数据库:" + databasename + "成功!");
}
}
catch (Exception ex)
{
LogHelper.Debug(ex);
}
}
b、在写入高频数据的时候,需要使用事务,如果反复进行(打开->插入>关闭)操作,sqlite效率1秒钟插入也就2条,使用程序进行插入就会发现输入的频率远低于获取到的数据,大量的数据被缓存到内存中,为了处理入库的速度慢,就要用到事务,事务流程:
①打开连接
②开始事务
③循环在内存中执行插入命令
④提交事务写入本地文件,如果出错回滚事务
⑤关闭连接
代码见下图,开始事务后通过SQLiteCommand的ExecuteNonQuery()方法进行内存提交
using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
DbTransaction trans = null;
try
{
cmd.Connection = conn;
conn.Open();
//开启事务
using (trans = conn.BeginTransaction())
{
while (_list.Count > 0)
{
GpsDataClass _gps = _list[0];
try
{
if (_gps != null)
{
SQLiteHelper sh = new SQLiteHelper(cmd);
var dic = new Dictionary();
dic["CarPlate"] = _gps.CarPlate;
dic["CarIpAddress"] = _gps.CarIpAddress;
dic["PosX1"] = _gps.PosX1;
dic["PosY1"] = _gps.PosY1;
dic["PosZ1"] = _gps.PosZ1;
dic["Heading1"] = _gps.Heading1;
dic["PosStatus1"] = _gps.PosStatus1;
dic["NumF1"] = _gps.NumF1;
dic["NumB1"] = _gps.NumB1;
dic["PosX2"] = _gps.PosX2;
dic["PosY2"] = _gps.PosY2;
dic["PosZ2"] = _gps.PosZ2;
dic["Heading2"] = _gps.Heading2;
dic["PosStatus2"] = _gps.PosStatus2;
dic["NumF2"] = _gps.NumF2;
dic["NumB2"] = _gps.NumB2;
dic["Speed"] = _gps.Speed;
dic["Signal"] = _gps.Signal;
dic["NowTime"] = _gps.NowTime;
sh.Insert("GpsRecord", dic);
_list.RemoveAt(0);
}
}
catch (Exception ex)
{
LogHelper.Debug(ex);
}
}
trans.Commit();
}
}
catch (Exception ex)
{
trans.Rollback();
LogHelper.Debug(ex);
}
conn.Close();
}
}
Original: https://blog.csdn.net/evint888/article/details/122331724
Author: 冀石程序猿
Title: C# SQLite库使用
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/815852/
转载文章受原作者版权保护。转载请注明原作者出处!