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#程序设计有所帮助。

(0)

相关推荐

  • C#操作SQLite数据库之读写数据库的方法

    本文实例讲述了C#操作SQLite数据库之读写数据库的方法.分享给大家供大家参考,具体如下: 这里演示读写数据库并在窗体(Form)中显示其数据,其方式为: 读: Database(SQLite) -> DataAdapter -> DataSet -> DataGridView 写: Database(SQLite) <- DataAdapter <- DataSet <- DataGridView 1.假设现有数据库表student,其字段如下: ID(自增字段,主

  • C#简单查询SQLite数据库是否存在数据的方法

    本文实例讲述了C#简单查询SQLite数据库是否存在数据的方法.分享给大家供大家参考,具体如下: //sqlite数据库驱动组件 using System.Data.SQLite; //插入数据库函数 int SQLquery(string sql) { try { //打开数据库 SQLiteConnection conn = new SQLiteConnection(); SQLiteConnectionStringBuilder connstr = new SQLiteConnection

  • C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法

    本文实例讲述了C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法.分享给大家供大家参考.具体如下: 这个类不是我实现的,英文原文地址为http://www.eggheadcafe.com/articles/20050315.asp,这里修改了原文中分析sql语句参数的方法,将方法名修改为AttachParameters,将其修饰符修改为private,并直接传递command到这个方法,直接绑定参数到comand.修改后的代码如下 using System;

  • C# SQLite事务操作方法分析

    本文实例讲述了C# SQLite事务操作方法.分享给大家供大家参考,具体如下: 在 C#中执行Sqlite数据库事务有两种方式:SQL代码和C#代码 1. SQL代码: BEGIN- COMMIT /ROLLBACK 2. C#代码: using (SQLiteConnection conn = SqliteHelper.GetSQLiteConnection()) { DbTransaction trans = conn.BeginTransaction(); try { //Sql语句 tr

  • C#操作SQLite数据库方法小结(创建,连接,插入,查询,删除等)

    本文实例讲述了C#操作SQLite数据库方法.分享给大家供大家参考,具体如下: SQLite介绍 SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. SQLite是一个开源.免费的小型RDBMS(关系型数据库),能独立运行.无服务器.零配置.支持事物,用C实现,内存占用较小,支持绝大数的SQ

  • c#几种数据库的大数据批量插入(SqlServer、Oracle、SQLite和MySql)

    在之前只知道SqlServer支持数据批量插入,殊不知道Oracle.SQLite和MySql也是支持的,不过Oracle需要使用Orace.DataAccess驱动,今天就贴出几种数据库的批量插入解决方法. 首先说一下,IProvider里有一个用于实现批量插入的插件服务接口IBatcherProvider,此接口在前一篇文章中已经提到过了. /// <summary> /// 提供数据批量处理的方法. /// </summary> public interface IBatch

  • C#/.Net 中快速批量给SQLite数据库插入测试数据

    使用transaction: var stopwatch = new Stopwatch(); using (var cmd = new SQLiteCommand(db_con)) using (var transaction = db_con.BeginTransaction()) { stopwatch.Reset(); stopwatch.Start(); foreach (var item in sorted) { sql = string.Format("insert into db

  • C# SQLite序列操作实现方法详解

    本文实例讲述了C# SQLite序列操作实现方法.分享给大家供大家参考,具体如下: sqlite 不能直接创建自定义函数,不能像 sql server中那样方便创建并使用.不过我们照样可以创建它,创建成功后,我们照样可以随心所欲(比如批量更新等) 序列是一个数据库中很常用的操作,在其它关系型数据库创建是相当简单的,但Sqlite不是很方便,因为它不能直接创建自定义函数 1.先创建一个表示序列的表: CREATE TABLE SEQUENCE ( SEQ_NAME VARCHAR(50) NOT

  • C#解决SQlite并发异常问题的方法(使用读写锁)

    本文实例讲述了C#解决SQlite并发异常问题的方法.分享给大家供大家参考,具体如下: 使用C#访问sqlite时,常会遇到多线程并发导致SQLITE数据库损坏的问题. SQLite是文件级别的数据库,其锁也是文件级别的:多个线程可以同时读,但是同时只能有一个线程写.Android提供了SqliteOpenHelper类,加入Java的锁机制以便调用.但在C#中未提供类似功能. 作者利用读写锁(ReaderWriterLock),达到了多线程安全访问的目标. using System; usin

  • C#操作SQLite方法实例详解

    本文实例讲述了C#操作SQLite方法.分享给大家供大家参考.具体分析如下: 地址: System.Data.Sqlite入手... 首先import/using: 复制代码 代码如下: using System.Data.SQLite; Connection和Command: private SQLiteConnection conn; private SQLiteCommand cmd; 连接db: conn = new SQLiteConnection("Data Source=c:\\t

  • C#简单访问SQLite数据库的方法(安装,连接,查询等)

    本文实例讲述了C#简单访问SQLite数据库的方法.分享给大家供大家参考,具体如下: 下载最新版SQLite(http://www.sqlite.org/download.html),其他版本也可以,这里使用的版本是sqlite-3_6_6_1 a.解压后copy c:\sqlite-3_6_6_1 b.进入cmd模式,进入sqlite-3_6_6_1目录,执行sqlite3 mytest.db c. create table test (seq int,desc varchar(8)); in

  • C#操作SQLite数据库帮助类详解

    本文实例讲述了C#操作SQLite数据库帮助类.分享给大家供大家参考,具体如下: 最近有WPF做客户端,需要离线操作存储数据,在项目中考虑使用Sqlite嵌入式数据库,在网上找了不少资料,最终整理出一个公共的帮助类. Sqlite是一个非常小巧的数据库,基本上具备关系型数据库操作的大多数功能,Sql语法也大同小异.下面是我整理的帮助类代码: 1.获取 SQLiteConnection 对象,传入数据库有地址即可. /// <summary> /// 获得连接对象 /// </summar

随机推荐