pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

C#中增加SQLite事務操作支持與使用方法

這篇文章主要介紹了C#中增加SQLite事務操作支持與使用方法,結合實例形式分析了C#中針對SQLite事務操作的添加及使用技巧,需要的朋友可以參考下

本文實例講述了C#中增加SQLite事務操作支持與使用方法。分享給大家供大家參考,具體如下:

在C#中使用Sqlite增加對transaction支持


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
namespace Simple_Disk_Catalog
{
  public class SQLiteDatabase
  {
    String DBConnection;
    private readonly SQLiteTransaction _sqLiteTransaction;
    private readonly SQLiteConnection _sqLiteConnection;
    private readonly bool _transaction;
    /// <summary>
    ///   Default Constructor for SQLiteDatabase Class.
    /// </summary>
    /// <param name="transaction">Allow programmers to insert, update and delete values in one transaction</param>
    public SQLiteDatabase(bool transaction = false)
    {
      _transaction = transaction;
      DBConnection = "Data Source=recipes.s3db";
      if (transaction)
      {
        _sqLiteConnection = new SQLiteConnection(DBConnection);
        _sqLiteConnection.Open();
        _sqLiteTransaction = _sqLiteConnection.BeginTransaction();
      }
    }
    /// <summary>
    ///   Single Param Constructor for specifying the DB file.
    /// </summary>
    /// <param name="inputFile">The File containing the DB</param>
    public SQLiteDatabase(String inputFile)
    {
      DBConnection = String.Format("Data Source={0}", inputFile);
    }
    /// <summary>
    ///   Commit transaction to the database.
    /// </summary>
    public void CommitTransaction()
    {
      _sqLiteTransaction.Commit();
      _sqLiteTransaction.Dispose();
      _sqLiteConnection.Close();
      _sqLiteConnection.Dispose();
    }
    /// <summary>
    ///   Single Param Constructor for specifying advanced connection options.
    /// </summary>
    /// <param name="connectionOpts">A dictionary containing all desired options and their values</param>
    public SQLiteDatabase(Dictionary<String, String> connectionOpts)
    {
      String str = connectionOpts.Aggregate("", (current, row) => current + String.Format("{0}={1}; ", row.Key, row.Value));
      str = str.Trim().Substring(0, str.Length - 1);
      DBConnection = str;
    }
    /// <summary>
    ///   Allows the programmer to create new database file.
    /// </summary>
    /// <param name="filePath">Full path of a new database file.</param>
    /// <returns>true or false to represent success or failure.</returns>
    public static bool CreateDB(string filePath)
    {
      try
      {
        SQLiteConnection.CreateFile(filePath);
        return true;
      }
      catch (Exception e)
      {
        MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
        return false;
      }
    }
    /// <summary>
    ///   Allows the programmer to run a query against the Database.
    /// </summary>
    /// <param name="sql">The SQL to run</param>
    /// <param name="allowDBNullColumns">Allow null value for columns in this collection.</param>
    /// <returns>A DataTable containing the result set.</returns>
    public DataTable GetDataTable(string sql, IEnumerable<string> allowDBNullColumns = null)
    {
      var dt = new DataTable();
      if (allowDBNullColumns != null)
        foreach (var s in allowDBNullColumns)
        {
          dt.Columns.Add(s);
          dt.Columns[s].AllowDBNull = true;
        }
      try
      {
        var cnn = new SQLiteConnection(DBConnection);
        cnn.Open();
        var mycommand = new SQLiteCommand(cnn) {CommandText = sql};
        var reader = mycommand.ExecuteReader();
        dt.Load(reader);
        reader.Close();
        cnn.Close();
      }
      catch (Exception e)
      {
        throw new Exception(e.Message);
      }
      return dt;
    }
    public string RetrieveOriginal(string value)
    {
      return
        value.Replace("&", "&").Replace("<", "<").Replace(">", "<").Replace(""", "\"").Replace(
          "'", "'");
    }
    /// <summary>
    ///   Allows the programmer to interact with the database for purposes other than a query.
    /// </summary>
    /// <param name="sql">The SQL to be run.</param>
    /// <returns>An Integer containing the number of rows updated.</returns>
    public int ExecuteNonQuery(string sql)
    {
      if (!_transaction)
      {
        var cnn = new SQLiteConnection(DBConnection);
        cnn.Open();
        var mycommand = new SQLiteCommand(cnn) {CommandText = sql};
        var rowsUpdated = mycommand.ExecuteNonQuery();
        cnn.Close();
        return rowsUpdated;
      }
      else
      {
        var mycommand = new SQLiteCommand(_sqLiteConnection) { CommandText = sql };
        return mycommand.ExecuteNonQuery();
      }
    }
    /// <summary>
    ///   Allows the programmer to retrieve single items from the DB.
    /// </summary>
    /// <param name="sql">The query to run.</param>
    /// <returns>A string.</returns>
    public string ExecuteScalar(string sql)
    {
      if (!_transaction)
      {
        var cnn = new SQLiteConnection(DBConnection);
        cnn.Open();
        var mycommand = new SQLiteCommand(cnn) {CommandText = sql};
        var value = mycommand.ExecuteScalar();
        cnn.Close();
        return value != null ? value.ToString() : "";
      }
      else
      {
        var sqLiteCommand = new SQLiteCommand(_sqLiteConnection) { CommandText = sql };
        var value = sqLiteCommand.ExecuteScalar();
        return value != null ? value.ToString() : "";
      }
    }
    /// <summary>
    ///   Allows the programmer to easily update rows in the DB.
    /// </summary>
    /// <param name="tableName">The table to update.</param>
    /// <param name="data">A dictionary containing Column names and their new values.</param>
    /// <param name="where">The where clause for the update statement.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool Update(String tableName, Dictionary<String, String> data, String where)
    {
      String vals = "";
      Boolean returnCode = true;
      if (data.Count >= 1)
      {
        vals = data.Aggregate(vals, (current, val) => current + String.Format(" {0} = '{1}',", val.Key.ToString(CultureInfo.InvariantCulture), val.Value.ToString(CultureInfo.InvariantCulture)));
        vals = vals.Substring(0, vals.Length - 1);
      }
      try
      {
        ExecuteNonQuery(String.Format("update {0} set {1} where {2};", tableName, vals, where));
      }
      catch
      {
        returnCode = false;
      }
      return returnCode;
    }
    /// <summary>
    ///   Allows the programmer to easily delete rows from the DB.
    /// </summary>
    /// <param name="tableName">The table from which to delete.</param>
    /// <param name="where">The where clause for the delete.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool Delete(String tableName, String where)
    {
      Boolean returnCode = true;
      try
      {
        ExecuteNonQuery(String.Format("delete from {0} where {1};", tableName, where));
      }
      catch (Exception fail)
      {
        MessageBox.Show(fail.Message, fail.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
        returnCode = false;
      }
      return returnCode;
    }
    /// <summary>
    ///   Allows the programmer to easily insert into the DB
    /// </summary>
    /// <param name="tableName">The table into which we insert the data.</param>
    /// <param name="data">A dictionary containing the column names and data for the insert.</param>
    /// <returns>returns last inserted row id if it's value is zero than it means failure.</returns>
    public long Insert(String tableName, Dictionary<String, String> data)
    {
      String columns = "";
      String values = "";
      String value;
      foreach (KeyValuePair<String, String> val in data)
      {
        columns += String.Format(" {0},", val.Key.ToString(CultureInfo.InvariantCulture));
        values += String.Format(" '{0}',", val.Value);
      }
      columns = columns.Substring(0, columns.Length - 1);
      values = values.Substring(0, values.Length - 1);
      try
      {
        if (!_transaction)
        {
          var cnn = new SQLiteConnection(DBConnection);
          cnn.Open();
          var sqLiteCommand = new SQLiteCommand(cnn)
                    {
                      CommandText =
                        String.Format("insert into {0}({1}) values({2});", tableName, columns,
                               values)
                    };
          sqLiteCommand.ExecuteNonQuery();
          sqLiteCommand = new SQLiteCommand(cnn) { CommandText = "SELECT last_insert_rowid()" };
          value = sqLiteCommand.ExecuteScalar().ToString();
        }
        else
        {
          ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
          value = ExecuteScalar("SELECT last_insert_rowid()");
        }
      }
      catch (Exception fail)
      {
        MessageBox.Show(fail.Message, fail.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
        return 0;
      }
      return long.Parse(value);
    }
    /// <summary>
    ///   Allows the programmer to easily delete all data from the DB.
    /// </summary>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool ClearDB()
    {
      try
      {
        var tables = GetDataTable("select NAME from SQLITE_MASTER where type='table' order by NAME;");
        foreach (DataRow table in tables.Rows)
        {
          ClearTable(table["NAME"].ToString());
        }
        return true;
      }
      catch
      {
        return false;
      }
    }
    /// <summary>
    ///   Allows the user to easily clear all data from a specific table.
    /// </summary>
    /// <param name="table">The name of the table to clear.</param>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool ClearTable(String table)
    {
      try
      {
        ExecuteNonQuery(String.Format("delete from {0};", table));
        return true;
      }
      catch
      {
        return false;
      }
    }
    /// <summary>
    ///   Allows the user to easily reduce size of database.
    /// </summary>
    /// <returns>A boolean true or false to signify success or failure.</returns>
    public bool CompactDB()
    {
      try
      {
        ExecuteNonQuery("Vacuum;");
        return true;
      }
      catch (Exception)
      {
        return false;
      }
    }
  }
}

更多關于C#相關內容感興趣的讀者可查看本站專題:《C#常見數據庫操作技巧匯總》、《C#常見控件用法教程》、《C#窗體操作技巧匯總》、《C#數據結構與算法教程》、《C#面向對象程序設計入門教程》及《C#程序設計之線程使用技巧總結》

希望本文所述對大家C#程序設計有所幫助。

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

這篇文章主要介紹了C# 將Access中以時間段條件查詢的數據添加到ListView中,需要的朋友可以參考下
這篇文章主要介紹了使用C#創建Windows服務的實例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
這篇文章主要介紹了C#身份證識別相關技術詳解,具有一定的參考價值,感興趣的小伙伴們可以參考一下
這篇文章主要為大家詳細介紹了C#中TCP粘包問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
這篇文章主要介紹了C#實現的海盜分金算法,結合具體實例形式分析了海盜分金算法的原理與C#相應實現技巧,需要的朋友可以參考下
這篇文章主要為大家詳細介紹了C#操作INI配置文件示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
主站蜘蛛池模板: 华禹护栏|锌钢护栏_阳台护栏_护栏厂家-华禹专注阳台护栏、楼梯栏杆、百叶窗、空调架、基坑护栏、道路护栏等锌钢护栏产品的生产销售。 | 100_150_200_250_300_350_400公斤压力空气压缩机-舰艇航天配套厂家 | pbt头梳丝_牙刷丝_尼龙毛刷丝_PP塑料纤维合成毛丝定制厂_广州明旺 | 冲击式破碎机-冲击式制砂机-移动碎石机厂家_青州市富康机械有限公司 | 工业硝酸钠,硝酸钠厂家-淄博「文海工贸」 | 塑钢件_塑钢门窗配件_塑钢配件厂家-文安县启泰金属制品有限公司 深圳南财多媒体有限公司介绍 | 科箭WMS仓库管理软件-TMS物流管理系统-科箭SaaS云服务 | 国产离子色谱仪,红外分光测油仪,自动烟尘烟气测试仪-青岛埃仑通用科技有限公司 | 安徽免检低氮锅炉_合肥燃油锅炉_安徽蒸汽发生器_合肥燃气锅炉-合肥扬诺锅炉有限公司 | 赛默飞Thermo veritiproPCR仪|ProFlex3 x 32PCR系统|Countess3细胞计数仪|371|3111二氧化碳培养箱|Mirco17R|Mirco21R离心机|仟诺生物 | 影像测量仪_三坐标测量机_一键式二次元_全自动影像测量仪-广东妙机精密科技股份有限公司 | 东亚液氮罐-液氮生物容器-乐山市东亚机电工贸有限公司 | 钢制暖气片散热器_天津钢制暖气片_卡麦罗散热器厂家 | 耐高温风管_耐高温软管_食品级软管_吸尘管_钢丝软管_卫生级软管_塑料波纹管-东莞市鑫翔宇软管有限公司 | 陶瓷砂磨机,盘式砂磨机,棒销式砂磨机-无锡市少宏粉体科技有限公司 | 防爆电机-高压防爆电机-ybx4电动机厂家-河南省南洋防爆电机有限公司 | 海德莱电力(HYDELEY)-无功补偿元器件生产厂家-二十年专业从事电力电容器 | pH污水传感器电极,溶解氧电极传感器-上海科蓝仪表科技有限公司 | 塑木弯曲试验机_铜带拉伸强度试验机_拉压力测试台-倾技百科 | 网带通过式抛丸机,,网带式打砂机,吊钩式,抛丸机,中山抛丸机生产厂家,江门抛丸机,佛山吊钩式,东莞抛丸机,中山市泰达自动化设备有限公司 | 水成膜泡沫灭火剂_氟蛋白泡沫液_河南新乡骏华消防科技厂家 | 耳模扫描仪-定制耳机设计软件-DLP打印机-asiga打印机-fitshape「飞特西普」 | 硅胶制品-硅橡胶制品-东莞硅胶制品厂家-广东帝博科技有限公司 | 多米诺-多米诺世界纪录团队-多米诺世界-多米诺团队培训-多米诺公关活动-多米诺创意广告-多米诺大型表演-多米诺专业赛事 | 扒渣机厂家_扒渣机价格_矿用扒渣机_铣挖机_撬毛台车_襄阳永力通扒渣机公司 | 购买舔盐、舔砖、矿物质盐压块机,鱼饵、鱼饲料压块机--请到杜甫机械 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库-首页-东莞市傲马网络科技有限公司 | 无缝钢管-聊城无缝钢管-小口径无缝钢管-大口径无缝钢管 - 聊城宽达钢管有限公司 | 背压阀|减压器|不锈钢减压器|减压阀|卫生级背压阀|单向阀|背压阀厂家-上海沃原自控阀门有限公司 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 升降机-高空作业车租赁-蜘蛛车-曲臂式伸缩臂剪叉式液压升降平台-脚手架-【普雷斯特公司厂家】 | Maneurop/美优乐压缩机,活塞压缩机,型号规格,技术参数,尺寸图片,价格经销商 | 电子元器件呆滞料_元器件临期库存清仓尾料_尾料优选现货采购处理交易商城 | 北京京云律师事务所| 带压开孔_带压堵漏_带压封堵-菏泽金升管道工程有限公司 | 高低温试验箱-模拟高低温试验箱订制-北京普桑达仪器科技有限公司【官网】 | 代理记账_公司起名核名_公司注册_工商注册-睿婕实业有限公司 | 杭州中央空调维修_冷却塔/新风机柜/热水器/锅炉除垢清洗_除垢剂_风机盘管_冷凝器清洗-杭州亿诺能源有限公司 | 温湿度记录纸_圆盘_横河记录纸|霍尼韦尔记录仪-广州汤米斯机电设备有限公司 | 便携式高压氧舱-微压氧舱-核生化洗消系统-公众洗消站-洗消帐篷-北京利盟救援 | 上海新光明泵业制造有限公司-电动隔膜泵,气动隔膜泵,卧式|立式离心泵厂家 | 仓储货架_南京货架_钢制托盘_仓储笼_隔离网_环球零件盒_诺力液压车_货架-南京一品仓储设备制造公司 |