C# SQLite数据库 访问封装类

在客户端配置文件节点下,添加:


其中【localdb】是本地SQLite数据库的名称,【config/local.db】是在当前程序运行目录下SQLite数据库位置

C# SQLite数据库  访问封装类代码:

 ///     /// 本类为SQLite数据库帮助静态类,使用时只需直接调用即可,无需实例化    ///     public static class SQLiteHelper    {        // Application.StartupPath        public static string LocalDbConnectionString = ConfigurationManager.ConnectionStrings["localdb"].ConnectionString;        #region ExecuteNonQuery        ///         /// 执行数据库操作(新增、更新或删除)        ///         /// 连接字符串        /// SqlCommand对象        /// 所受影响的行数        public static int ExecuteNonQuery(string connectionString, SQLiteCommand cmd)        {            int result = 0;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            using (SQLiteConnection con = new SQLiteConnection(connectionString))            {                SQLiteTransaction trans = null;                PrepareCommand(cmd, con, ref trans, true, cmd.CommandType, cmd.CommandText);                try                {                    result = cmd.ExecuteNonQuery();                    trans.Commit();                }                catch (Exception ex)                {                    trans.Rollback();                    throw ex;                }            }            return result;        }        ///         /// 执行数据库操作(新增、更新或删除)        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// 所受影响的行数        public static int ExecuteNonQuery(string connectionString, string commandText, CommandType commandType)        {            int result = 0;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            SQLiteCommand cmd = new SQLiteCommand();            using (SQLiteConnection con = new SQLiteConnection(connectionString))            {                SQLiteTransaction trans = null;                PrepareCommand(cmd, con, ref trans, true, commandType, commandText);                try                {                    result = cmd.ExecuteNonQuery();                    trans.Commit();                }                catch (Exception ex)                {                    trans.Rollback();                    throw ex;                }            }            return result;        }        ///         /// 执行数据库操作(新增、更新或删除)        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// SQL参数对象        /// 所受影响的行数        public static int ExecuteNonQuery(string connectionString, string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)        {            int result = 0;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            SQLiteCommand cmd = new SQLiteCommand();            using (SQLiteConnection con = new SQLiteConnection(connectionString))            {                SQLiteTransaction trans = null;                PrepareCommand(cmd, con, ref trans, true, commandType, commandText);                try                {                    result = cmd.ExecuteNonQuery();                    trans.Commit();                }                catch (Exception ex)                {                    trans.Rollback();                    throw ex;                }            }            return result;        }        #endregion        #region ExecuteScalar        ///         /// 执行数据库操作(新增、更新或删除)同时返回执行后查询所得的第1行第1列数据        ///         /// 连接字符串        /// SqlCommand对象        /// 查询所得的第1行第1列数据        public static object ExecuteScalar(string connectionString, SQLiteCommand cmd)        {            object result = 0;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            using (SQLiteConnection con = new SQLiteConnection(connectionString))            {                SQLiteTransaction trans = null;                PrepareCommand(cmd, con, ref trans, true, cmd.CommandType, cmd.CommandText);                try                {                    result = cmd.ExecuteScalar();                    trans.Commit();                }                catch (Exception ex)                {                    trans.Rollback();                    throw ex;                }            }            return result;        }        ///         /// 执行数据库操作(新增、更新或删除)同时返回执行后查询所得的第1行第1列数据        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// 查询所得的第1行第1列数据        public static object ExecuteScalar(string connectionString, string commandText, CommandType commandType)        {            object result = 0;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            SQLiteCommand cmd = new SQLiteCommand();            using (SQLiteConnection con = new SQLiteConnection(connectionString))            {                SQLiteTransaction trans = null;                PrepareCommand(cmd, con, ref trans, true, commandType, commandText);                try                {                    result = cmd.ExecuteScalar();                    trans.Commit();                }                catch (Exception ex)                {                    trans.Rollback();                    throw ex;                }            }            return result;        }        ///         /// 执行数据库操作(新增、更新或删除)同时返回执行后查询所得的第1行第1列数据        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// SQL参数对象        /// 查询所得的第1行第1列数据        public static object ExecuteScalar(string connectionString, string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)        {            object result = 0;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            SQLiteCommand cmd = new SQLiteCommand();            using (SQLiteConnection con = new SQLiteConnection(connectionString))            {                SQLiteTransaction trans = null;                PrepareCommand(cmd, con, ref trans, true, commandType, commandText);                try                {                    result = cmd.ExecuteScalar();                    trans.Commit();                }                catch (Exception ex)                {                    trans.Rollback();                    throw ex;                }            }            return result;        }        #endregion        #region ExecuteReader        ///         /// 执行数据库查询,返回SqlDataReader对象        ///         /// 连接字符串        /// SqlCommand对象        /// SqlDataReader对象        public static DbDataReader ExecuteReader(string connectionString, SQLiteCommand cmd)        {            DbDataReader reader = null;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            SQLiteConnection con = new SQLiteConnection(connectionString);            SQLiteTransaction trans = null;            PrepareCommand(cmd, con, ref trans, false, cmd.CommandType, cmd.CommandText);            try            {                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);            }            catch (Exception ex)            {                throw ex;            }            return reader;        }        ///         /// 执行数据库查询,返回SqlDataReader对象        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// SqlDataReader对象        public static DbDataReader ExecuteReader(string connectionString, string commandText, CommandType commandType)        {            DbDataReader reader = null;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            SQLiteConnection con = new SQLiteConnection(connectionString);            SQLiteCommand cmd = new SQLiteCommand();            SQLiteTransaction trans = null;            PrepareCommand(cmd, con, ref trans, false, commandType, commandText);            try            {                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);            }            catch (Exception ex)            {                throw ex;            }            return reader;        }        ///         /// 执行数据库查询,返回SqlDataReader对象        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// SQL参数对象        /// SqlDataReader对象        public static DbDataReader ExecuteReader(string connectionString, string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)        {            DbDataReader reader = null;            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            SQLiteConnection con = new SQLiteConnection(connectionString);            SQLiteCommand cmd = new SQLiteCommand();            SQLiteTransaction trans = null;            PrepareCommand(cmd, con, ref trans, false, commandType, commandText, cmdParms);            try            {                reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);            }            catch (Exception ex)            {                throw ex;            }            return reader;        }        #endregion        #region ExecuteDataSet        ///         /// 执行数据库查询,返回DataSet对象        ///         /// 连接字符串        /// SqlCommand对象        /// DataSet对象        public static DataSet ExecuteDataSet(string connectionString, SQLiteCommand cmd)        {            DataSet ds = new DataSet();            SQLiteConnection con = new SQLiteConnection(connectionString);            SQLiteTransaction trans = null;            PrepareCommand(cmd, con, 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;        }        ///         /// 执行数据库查询,返回DataSet对象        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// DataSet对象        public static DataSet ExecuteDataSet(string connectionString, string commandText, CommandType commandType)        {            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            DataSet ds = new DataSet();            SQLiteConnection con = new SQLiteConnection(connectionString);            SQLiteCommand cmd = new SQLiteCommand();            SQLiteTransaction trans = null;            PrepareCommand(cmd, con, ref trans, false, commandType, commandText);            try            {                SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);                sda.Fill(ds);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (con != null)                {                    if (con.State == ConnectionState.Open)                    {                        con.Close();                    }                }            }            return ds;        }        ///         /// 执行数据库查询,返回DataSet对象        ///         /// 连接字符串        /// 执行语句或存储过程名        /// 执行类型        /// SQL参数对象        /// DataSet对象        public static DataSet ExecuteDataSet(string connectionString, string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)        {            if (connectionString == null || connectionString.Length == 0)                throw new ArgumentNullException("connectionString");            if (commandText == null || commandText.Length == 0)                throw new ArgumentNullException("commandText");            DataSet ds = new DataSet();            SQLiteConnection con = new SQLiteConnection(connectionString);            SQLiteCommand cmd = new SQLiteCommand();            SQLiteTransaction trans = null;            PrepareCommand(cmd, con, ref trans, false, commandType, commandText, cmdParms);            try            {                SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);                sda.Fill(ds);            }            catch (Exception ex)            {                throw ex;            }            finally            {                if (con != null)                {                    if (con.State == ConnectionState.Open)                    {                        con.Close();                    }                }            }            return ds;        }        #endregion        #region 通用分页查询方法        ///         /// 通用分页查询方法        ///         /// 连接字符串        /// 表名        /// 查询字段名        /// where条件        /// 排序条件        /// 每页数据数量        /// 当前页数        /// 数据总量        /// DataTable数据表        public static DataTable SelectPaging(string connString, string tableName, string strColumns, string strWhere, string strOrder, int pageSize, int currentIndex, out int recordOut)        {            DataTable dt = new DataTable();            recordOut = Convert.ToInt32(ExecuteScalar(connString, "select count(*) from " + tableName, CommandType.Text));            string pagingTemplate = "select {0} from {1} where {2} order by {3} limit {4} offset {5} ";            int offsetCount = (currentIndex - 1) * pageSize;            string commandText = String.Format(pagingTemplate, strColumns, tableName, strWhere, strOrder, pageSize.ToString(), offsetCount.ToString());            using (DbDataReader reader = ExecuteReader(connString, commandText, CommandType.Text))            {                if (reader != null)                {                    dt.Load(reader);                }            }            return dt;        }        #endregion        #region  预处理Command对象,数据库链接,事务,需要执行的对象,参数等的初始化        ///         /// 预处理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)        {            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);            }        }        #endregion    }

使用demo:

 ///         /// 获取数据库关键字信息        ///         /// 分类        /// 版本        ///         private DataSet GetSystemDataBaseKeyWords(string category, string versions)        {            StringBuilder sql = new StringBuilder();            sql.Append("SELECT Keywords , Versions , Type , Description , Category  , Id , Extends ");            sql.Append(" FROM A_DataBaseKeyWords ");            sql.AppendFormat(" WHERE 1={0} ", "1");            if (!String.IsNullOrEmpty(category))            {                sql.AppendFormat(" AND Category='{0}'", category);            }            if (!String.IsNullOrEmpty(versions))            {                sql.AppendFormat(" AND Versions='{0}'", versions);            }            return SQLiteHelper.ExecuteDataSet(SQLiteHelper.LocalDbConnectionString, sql.ToString(), CommandType.Text);        }

以上就是C# SQLite数据库  访问封装类的内容,更多相关内容请关注PHP中文网(www.php.cn)!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1432220.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 06:22:49
下一篇 2025年12月17日 06:23:00

相关推荐

  • C# 异常处理(Catch Throw)IL分析

    1、catch throw的几种形式及性能影响: private void Form1_Click(object sender, EventArgs e) { try { } catch { throw; } } private void Form1_Load(object sender, Even…

    好文分享 2025年12月17日
    000
  • C# DataRow 比较

    /// /// dataRow比较 /// /// /// /// 需要比较的列名称 /// public static bool DataRowCompare(DataRow drA, DataRow drB, string[] columnNames) { bool flag = false; …

    好文分享 2025年12月17日
    000
  • C#基础知识整理:基础知识(5) 方法的重载

        老师都有讲课这个方法,一个老师先是在西部偏远山区,是站在教室里木头的黑板前讲课;过了几年表现好,调到了稍微好点的城市里,是坐在教室前用多媒体设备讲课;又过了几年考博士了,毕业后继续当老师,不过现在是躺在家里对着电脑远程授课。都是讲课这个方法,不同的条件下(参数不同)有不同的执行过程和输出结果…

    2025年12月17日
    000
  • C#基础知识整理:基础知识(6) 抽象类和抽象方法

    在实际项目中,当我们设计一个父类时,经常会遇到这个类不能确定它的具体执行流程的。比如我设计一个文件类: public class AFile { private string name = string.Empty; private string path = string.Empty; priva…

    好文分享 2025年12月17日
    000
  • C#基础知识整理:基础知识(7) 方法的隐藏

    继承和抽象类中提到过,子类与父类的方法间有这些关系:子类直接使用父类方法(但是必须父类方法是public或protected类型);子类的方法覆盖父类方法(override);子类的方法重载父类方法(overload);看下面这种情况: public class YSchool { private …

    2025年12月17日
    000
  • C#基础知识整理:基础知识(8) 接口

        前面接触了抽象类,它的特点是子类必须实现abstract修饰的方法。以及还有virtual修饰的方法,virtual修饰的方法子类可以重写也可以不重写而直接使用。但是由于c#也是单继承的,所以定义一个父类,然后继承来扩展一些类的时候,会遇到不合适的情况。因为我们程序员是用程序语言来描述世界的…

    好文分享 2025年12月17日
    000
  • C#基础知识整理:基础知识(9) 接口的应用

        前面接触过接口的概念,其实接口就是一组方法、属性,然后谁继承了它,谁就要实现这组方法和属性。也就是说这个类具备了这个接口定义的一些能力。    接口的这种特性在平常的程序编写中是有很大作用的,往往完成一个大项目需要很多人同时完成,这样难免会有一些类都需要某些方法,而且执行流程都差不多。这是在…

    2025年12月17日
    000
  • C#基础知识整理:基础知识(10) 静态

        如果想访问某个类的方法或属性,一定要先实例化该类,然后用该类的对象加.号访问。比如:有一个用户类和一个处理密码(加密和解密)的类。没生成一个用户实例后,处理密码类要对密码进行加密和解密。 using System;using System.Collections.Generic;using …

    2025年12月17日
    000
  • C#基础知识整理:基础知识(11) 值类型,引用类型

    c#是面向对象的语言,在面向对象的思想中,只有对象,所有事物都可以用类描述。所以比如这些,int,bool,char,string,double,long等都是类,那么像,30,2.5,”test”都是对应类的一个对象。 static void Main(string[] a…

    2025年12月17日
    000
  • C#基础知识整理:基础知识(12) 超类Object

        面向对象三大特性:封装,继承,多态。那么类是从哪里继承呢?在面向对象语言中有基类或者也叫做超类的概念,也就是所有类都是从这个类继承得来的,这个超类叫object。.net中是这样描述object类的:    支持 .net framework 类层次结构中的所有类,并为派生类提供低级别服务。…

    2025年12月17日
    000
  • C#基础知识整理:基础知识(13) 异常

        往往我们在写代码的时候,总会在运行中遇到某些问题而导致程序崩溃。这并不是编程人员的水平不行,而是由业务逻辑,操作系统,或者电脑等其它设备出现问题而造成,比如在c#中经常用到user32.dll里的一些方法,假如这个文件被删掉了,你的程序照样运行不了。当然作为一个有水平的程序员总会在写程序时是…

    好文分享 2025年12月17日
    000
  • C#基础知识整理:基础知识(14) 数组

    无论哪种语言,肯定会有集合的概念。而最简单,最直观的集合应该就是数组了,数组是在内存中连续的一段空间。看看c#中数组 的定义。1、int[] intArry ; intArry= new int[6]; 这里声明了一个int数组类型变量intArry,并保存一个具有6个单元的int数组对象; int…

    2025年12月17日
    000
  • C#基础知识整理 基础知识(18) 值类型的装箱和拆箱(一)

    仔细了解装箱和拆箱其实是很有趣的,首先来看为什么会装箱和拆箱呢?看下面一段代码: class Program { static void Main(string[] args) { ArrayList array = new ArrayList(); Point p;//分配一个 for (int …

    好文分享 2025年12月17日
    000
  • C#基础知识整理:C#类和结构(3)

    1、静态类和静态成员有哪些功能特性? 实现代码?    静态类和静态成员是指使用static关键字定义的类或成员,凡是static类的成员一定是static成员,不然会报错的。静态类和成员的一大特点就是它们是独一无二的。如果是static类,那么它是不能实例化的,而且加载在内存中只有一个;如果是st…

    2025年12月17日
    000
  • C#基础知识整理:C#类和结构(4)

    1、什么是接口? 功能特性? 实现代码?    接口就是使用interface关键字定义的,由类的成员的组合组成的,描述一些功能的一组规范。在c#中可以看到,系统的一些接口都是这样命名的:icomparable(类型的比较方法)、icloneable(支持克隆)、idisposable(释放资源)等…

    2025年12月17日
    000
  • C#基础知识整理:基础知识(1) Main方法

    千里之行始于足下,掌握某一项技能,都是要从最基本的东西开始。温故而知新,一件小事当你在不同的境遇,不同的时间下去做,总能获得意想不到的体验和收获。那么首先就从main方法开始吧, //using关键字在该处的作用是引入一个“外部程序集”,System是微软提供的.net平台最基本程序集,所有.net…

    好文分享 2025年12月17日
    000
  • C#基础知识整理:基础知识(2) 类

        类,是面向对象语言的基础。类的三大特性:封装、继承、多态。最基本的特性就是封装性。程序员用程序描述世界,将世界的所有事物都看成对象,怎么描述这个对象?那就是类了。也就是用类来封装对象。用书上的话说,类是具有相同属性和行为的对象的抽象。宝马汽车、别克汽车、五菱之光汽车… 基本具有相…

    2025年12月17日
    000
  • C#基础知识整理:基础知识(3) 类的构造

    我们定义了yschool,yteacher类,实例化对象时: YSchool shool1 = new YSchool(); shool1.ID = 1; shool1.Name = “清华附中”; YSchool school2 = new YSchool(); school2.ID = 2; s…

    好文分享 2025年12月17日
    000
  • C#基础知识整理:基础知识(4) 继承

        前面提到过,面向对象的三大特性:封装性、继承性和多态性。封装在前面类的定义里也了解的差不多透彻了,现在看看继承的特性。继承实际是一个类对另一个类的扩展,后者称之为基类,前者称之为子类。继承就是子类拥有基类的一切属性和方法,子类还可以增加属性和方法。但是子类不能去掉父类的属性和方法。    当…

    2025年12月17日
    000
  • C# 快速排序

    c# 快速排序 using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Sort{ class QuickSorter { private static int[] myA…

    2025年12月17日
    000

发表回复

登录后才能评论
关注微信