C# SQLite库使用技巧
1、sqlite介绍
sqlite,是一款轻型的数据库,是遵守的acid关系型数据库管理系统,它包含在一个相对小的c库中。它的设计目标嵌入式是的,而且已经在很多中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百k的内存就够了。它能够支持windows/linux/unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 tcl、c#、php、java等。
sqlite is a software library that implements a self-contained, serverless, zero-configuration, transactional sql database engine.
sqlite是一个开源、免费的小型rdbms(关系型数据库),能独立运行、无服务器、零配置、支持事物,用c实现,内存占用较小,支持绝大数的sql92标准。
sqlite数据库官方主页:http://www.sqlite.org/index.html
2、c#下调用sqlite数据库
在nuget程序包内,搜索system.data.sqlite,安装sqlite类库
3、在c#程序内添加sqlitehelper
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"; /// <summary> /// 执行数据库操作(新增、更新或删除) /// </summary> /// <param name="cmdstr">连接字符串</param> /// <param name="cmdparms">sqlcommand对象</param> /// <returns>受影响的行数</returns> 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; } /// <summary> /// 预处理command对象,数据库链接,事务,需要执行的对象,参数等的初始化 /// </summary> /// <param name="cmd">command对象</param> /// <param name="conn">connection对象</param> /// <param name="trans">transcation对象</param> /// <param name="usetrans">是否使用事务</param> /// <param name="cmdtype">sql字符串执行类型</param> /// <param name="cmdtext">sql text</param> /// <param name="cmdparms">sqliteparameters to use in the command</param> 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 { } } /// <summary> /// 数据库查询 /// </summary> /// <param name="cmdstr">sql语句</param> /// <param name="tablename">表名</param> /// <returns>dataset对象</returns> 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名称的数据库
/// <summary> /// 数据库路径 /// </summary> private static string databasepath = appdomain.currentdomain.basedirectory + "database\\"; /// <summary> /// 数据库名称 /// </summary> private const string databasename = "analysis.db"; /// <summary> /// 创建数据库 /// </summary> 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<string, object>(); 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(); } }
到此这篇关于c# sqlite库使用的文章就介绍到这了,更多相关c# sqlite库使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!