热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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;
    /// 
    ///   Default Constructor for SQLiteDatabase Class.
    /// 
    /// Allow programmers to insert, update and delete values in one transaction
    public SQLiteDatabase(bool transaction = false)
    {
      _transaction = transaction;
      DBCOnnection= "Data Source=recipes.s3db";
      if (transaction)
      {
        _sqLiteCOnnection= new SQLiteConnection(DBConnection);
        _sqLiteConnection.Open();
        _sqLiteTransaction = _sqLiteConnection.BeginTransaction();
      }
    }
    /// 
    ///   Single Param Constructor for specifying the DB file.
    /// 
    /// The File containing the DB
    public SQLiteDatabase(String inputFile)
    {
      DBCOnnection= String.Format("Data Source={0}", inputFile);
    }
    /// 
    ///   Commit transaction to the database.
    /// 
    public void CommitTransaction()
    {
      _sqLiteTransaction.Commit();
      _sqLiteTransaction.Dispose();
      _sqLiteConnection.Close();
      _sqLiteConnection.Dispose();
    }
    /// 
    ///   Single Param Constructor for specifying advanced connection options.
    /// 
    /// A dictionary containing all desired options and their values
    public SQLiteDatabase(Dictionary 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;
    }
    /// 
    ///   Allows the programmer to create new database file.
    /// 
    /// Full path of a new database file.
    /// true or false to represent success or failure.
    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;
      }
    }
    /// 
    ///   Allows the programmer to run a query against the Database.
    /// 
    /// The SQL to run
    /// Allow null value for columns in this collection.
    /// A DataTable containing the result set.
    public DataTable GetDataTable(string sql, IEnumerable 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(
          "'", "'");
    }
    /// 
    ///   Allows the programmer to interact with the database for purposes other than a query.
    /// 
    /// The SQL to be run.
    /// An Integer containing the number of rows updated.
    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();
      }
    }
    /// 
    ///   Allows the programmer to retrieve single items from the DB.
    /// 
    /// The query to run.
    /// A string.
    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 &#63; value.ToString() : "";
      }
      else
      {
        var sqLiteCommand = new SQLiteCommand(_sqLiteConnection) { CommandText = sql };
        var value = sqLiteCommand.ExecuteScalar();
        return value != null &#63; value.ToString() : "";
      }
    }
    /// 
    ///   Allows the programmer to easily update rows in the DB.
    /// 
    /// The table to update.
    /// A dictionary containing Column names and their new values.
    /// The where clause for the update statement.
    /// A boolean true or false to signify success or failure.
    public bool Update(String tableName, Dictionary 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;
    }
    /// 
    ///   Allows the programmer to easily delete rows from the DB.
    /// 
    /// The table from which to delete.
    /// The where clause for the delete.
    /// A boolean true or false to signify success or failure.
    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;
    }
    /// 
    ///   Allows the programmer to easily insert into the DB
    /// 
    /// The table into which we insert the data.
    /// A dictionary containing the column names and data for the insert.
    /// returns last inserted row id if it's value is zero than it means failure.
    public long Insert(String tableName, Dictionary data)
    {
      String columns = "";
      String values = "";
      String value;
      foreach (KeyValuePair 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);
    }
    /// 
    ///   Allows the programmer to easily delete all data from the DB.
    /// 
    /// A boolean true or false to signify success or failure.
    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;
      }
    }
    /// 
    ///   Allows the user to easily clear all data from a specific table.
    /// 
    /// The name of the table to clear.
    /// A boolean true or false to signify success or failure.
    public bool ClearTable(String table)
    {
      try
      {
        ExecuteNonQuery(String.Format("delete from {0};", table));
        return true;
      }
      catch
      {
        return false;
      }
    }
    /// 
    ///   Allows the user to easily reduce size of database.
    /// 
    /// A boolean true or false to signify success or failure.
    public bool CompactDB()
    {
      try
      {
        ExecuteNonQuery("Vacuum;");
        return true;
      }
      catch (Exception)
      {
        return false;
      }
    }
  }
}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#常见数据库操作技巧汇总》、《C#常见控件用法教程》、《C#窗体操作技巧汇总》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》

希望本文所述对大家C#程序设计有所帮助。


推荐阅读
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 本文是一位90后程序员分享的职业发展经验,从年薪3w到30w的薪资增长过程。文章回顾了自己的青春时光,包括与朋友一起玩DOTA的回忆,并附上了一段纪念DOTA青春的视频链接。作者还提到了一些与程序员相关的名词和团队,如Pis、蛛丝马迹、B神、LGD、EHOME等。通过分享自己的经验,作者希望能够给其他程序员提供一些职业发展的思路和启示。 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • php 垃圾回收 默认 打开,PHP垃圾回收机制详解
    PHP的基本GC概念PHP语言同其他语言一样,具有垃圾回收机制。那么今天我们要为大家讲解的内容就是关于PHP垃圾回收机制的相关问题。希望对大家有所帮助。PHPstrt ... [详细]
  • 5.单例模式classMarker(valcolor:String){类中的任何代码段作为构造函数的一部分println(Creating+this)over ... [详细]
  • 这一节是此方案设计的最核心部分,指针能否准确的定位出来是最关键的问题,在学习过程中,初步采用几种方案来尽可能的提高指针定位的精度: ... [详细]
  • Spark面试题汇总大全
    1RDD简介RDD是Spark最基本也是最根本的数据抽象,它具备像MapReduce等数据流模型的容错性,并且允许开发人员在大型集群上执行基于内存的计 ... [详细]
  • C#datatable序列化后整数带有小数点或者小数点变成整数原来datatable的列有个datatype属性,可以指定为int类型或者decimal类型的,如果指定int类型, ... [详细]
  • 安卓ndk开发!高级Android晋升之View渲染机制,附答案
    缘起深圳市腾讯计算机系统有限公司成立于1998年11月,是中国最大的互联网综合服务提供商之一,也是中国服务用户最多的互联网企业之一。腾讯业务多元化& ... [详细]
  • 动态分页实现
    Code分页存储过程CREATEprocedurePagersqlstrnvarchar(4000),--查询字符串currentpageint,--第N页pagesizeint- ... [详细]
  • 优酷如何去广告?优酷去广告方法
    优酷如何去广告?优酷应该是大家最常使用的视频播放器了,然而优酷的广告也是很多,那么要如何去除烦心的广告呢?下面小编给大家分享优酷去广告的小技巧,请大家笑纳!步骤如下:1、找到hos ... [详细]
author-avatar
唯爱WE创丶
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有