文档章节

轻量级 SQLite数据库帮助类 增删改查 分页

深圳大道
 深圳大道
发布于 2016/12/29 15:33
字数 1845
阅读 3
收藏 0
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SQLite; //引用
using System.Data;
using System.Data.Common;

namespace MSCL
{
    /// <summary>   
    /// 本类为SQLite数据库帮助类   
    /// 轻量级数据库SQLite的连接字符串写法:"Data Source=D:\database\test.s3db"   
    /// 轻量级数据库SQLite的加密后的连接字符串写法:"Data Source=Maximus.db;Version=3;Password=myPassword;"  
    /*
         string connStr = "Data Source=" + Server.MapPath("~/App_Data/test.db") + ";Version=3;Password=smile;";        
         DataSet ds = new DataSet();        
         MSCL.SqliteHelper sqlite = new MSCL.SqliteHelper(connStr);        
         ds = sqlite.ExecuteDataSet("Select * From LoginTable",CommandType.Text);
    */
    /// </summary>   
    public class SqliteHelper
    {
        //数据库连接字符串   
        private readonly string _conn = string.Empty;

        public SqliteHelper(string connectionString)
        {
            _conn = connectionString;
        }

        #region ExecuteNonQuery
        /// <summary>   
        /// 执行数据库操作(新增、更新或删除)   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="cmd">SqlCommand对象</param>   
        /// <returns>所受影响的行数</returns>   
        public int ExecuteNonQuery(SQLiteCommand cmd)
        {
            int result = 0;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            using (SQLiteConnection con = new SQLiteConnection(_conn))
            {
                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;
        }

        /// <summary>   
        /// 执行数据库操作(新增、更新或删除)   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <returns>所受影响的行数</returns>   
        public int ExecuteNonQuery(string commandText, CommandType commandType)
        {
            int result = 0;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");
            SQLiteCommand cmd = new SQLiteCommand();
            using (SQLiteConnection con = new SQLiteConnection(_conn))
            {
                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;
        }

        /// <summary>   
        /// 执行数据库操作(新增、更新或删除)   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <param name="cmdParms">SQL参数对象</param>   
        /// <returns>所受影响的行数</returns>   
        public int ExecuteNonQuery(string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)
        {
            int result = 0;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");

            SQLiteCommand cmd = new SQLiteCommand();
            using (SQLiteConnection con = new SQLiteConnection(_conn))
            {
                SQLiteTransaction trans = null;
                PrepareCommand(cmd, con, ref trans, true, commandType, commandText, cmdParms);
                try
                {
                    result = cmd.ExecuteNonQuery();
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
            }
            return result;
        }
        #endregion

        #region ExecuteScalar
        /// <summary>   
        /// 执行数据库操作(新增、更新或删除)同时返回执行后查询所得的第1行第1列数据   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="cmd">SqlCommand对象</param>   
        /// <returns>查询所得的第1行第1列数据</returns>   
        public object ExecuteScalar(SQLiteCommand cmd)
        {
            object result = 0;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            using (SQLiteConnection con = new SQLiteConnection(_conn))
            {
                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;
        }

        /// <summary>   
        /// 执行数据库操作(新增、更新或删除)同时返回执行后查询所得的第1行第1列数据   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <returns>查询所得的第1行第1列数据</returns>   
        public object ExecuteScalar(string commandText, CommandType commandType)
        {
            object result = 0;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");
            SQLiteCommand cmd = new SQLiteCommand();
            using (SQLiteConnection con = new SQLiteConnection(_conn))
            {
                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;
        }

        /// <summary>   
        /// 执行数据库操作(新增、更新或删除)同时返回执行后查询所得的第1行第1列数据   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <param name="cmdParms">SQL参数对象</param>   
        /// <returns>查询所得的第1行第1列数据</returns>   
        public object ExecuteScalar(string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)
        {
            object result = 0;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");

            SQLiteCommand cmd = new SQLiteCommand();
            using (SQLiteConnection con = new SQLiteConnection(_conn))
            {
                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
        /// <summary>   
        /// 执行数据库查询,返回SqlDataReader对象   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="cmd">SqlCommand对象</param>   
        /// <returns>SqlDataReader对象</returns>   
        public DbDataReader ExecuteReader(SQLiteCommand cmd)
        {
            DbDataReader reader = null;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");

            SQLiteConnection con = new SQLiteConnection(_conn);
            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;
        }

        /// <summary>   
        /// 执行数据库查询,返回SqlDataReader对象   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <returns>SqlDataReader对象</returns>   
        public DbDataReader ExecuteReader(string commandText, CommandType commandType)
        {
            DbDataReader reader = null;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");

            SQLiteConnection con = new SQLiteConnection(_conn);
            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;
        }

        /// <summary>   
        /// 执行数据库查询,返回SqlDataReader对象   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <param name="cmdParms">SQL参数对象</param>   
        /// <returns>SqlDataReader对象</returns>   
        public DbDataReader ExecuteReader(string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)
        {
            DbDataReader reader = null;
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");

            SQLiteConnection con = new SQLiteConnection(_conn);
            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
        /// <summary>   
        /// 执行数据库查询,返回DataSet对象   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="cmd">SqlCommand对象</param>   
        /// <returns>DataSet对象</returns>   
        public DataSet ExecuteDataSet(SQLiteCommand cmd)
        {
            DataSet ds = new DataSet();
            SQLiteConnection con = new SQLiteConnection(_conn);
            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;
        }

        /// <summary>   
        /// 执行数据库查询,返回DataSet对象   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <returns>DataSet对象</returns>   
        public DataSet ExecuteDataSet(string commandText, CommandType commandType)
        {
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");
            DataSet ds = new DataSet();
            SQLiteConnection con = new SQLiteConnection(_conn);
            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;
        }

        /// <summary>   
        /// 执行数据库查询,返回DataSet对象   
        /// </summary>   
        /// <param name="connectionString">连接字符串</param>   
        /// <param name="commandText">执行语句或存储过程名</param>   
        /// <param name="commandType">执行类型</param>   
        /// <param name="cmdParms">SQL参数对象</param>   
        /// <returns>DataSet对象</returns>   
        public DataSet ExecuteDataSet(string commandText, CommandType commandType, params SQLiteParameter[] cmdParms)
        {
            if (string.IsNullOrEmpty(_conn))
                throw new ArgumentNullException("Connection string is missing.");
            if (string.IsNullOrEmpty(commandText))
                throw new ArgumentNullException("commandText");
            DataSet ds = new DataSet();
            SQLiteConnection con = null;
            SQLiteCommand cmd = new SQLiteCommand();
            SQLiteTransaction trans = null;
            try
            {
                con = new SQLiteConnection(_conn);
                PrepareCommand(cmd, con, ref trans, false, commandType, commandText, cmdParms);
                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

        /// <summary>   
        /// 通用分页查询方法   
        /// </summary>   
        /// <param name="connString">连接字符串</param>   
        /// <param name="tableName">表名</param>   
        /// <param name="strColumns">查询字段名</param>   
        /// <param name="strWhere">where条件</param>   
        /// <param name="strOrder">排序条件</param>   
        /// <param name="pageSize">每页数据数量</param>   
        /// <param name="currentIndex">当前页数</param>   
        /// <param name="recordOut">数据总量</param>   
        /// <returns>DataTable数据表</returns>   
        public DataTable SelectPaging(string tableName, string strColumns, string strWhere, string strOrder, int pageSize, int currentIndex, out int recordOut)
        {
            DataTable dt = new DataTable();
            //查询总数   
            string countSql = "select count(*) from " + tableName + " where {0}";
            countSql = String.Format(countSql, strWhere);
            recordOut = Convert.ToInt32(ExecuteScalar(countSql, 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(commandText, CommandType.Text))
            {
                if (reader != null)
                {
                    dt.Load(reader);
                }
            }
            return dt;
        }

        /// <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 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);
            }
        }
    }
}

本文转载自:http://blog.csdn.net/smartsmile2012/article/details/8167017

深圳大道
粉丝 3
博文 877
码字总数 0
作品 0
深圳
架构师
私信 提问
一起学Android之Sqlite

概述 Android对Sqlite提供了完全友好的支持,在应用程序内部,都可以通过名称访问任何的数据库。建议通过SQLiteOpenHelpe的子类并通过重写onCreate() 方法进行创建数据表。本文主要讲解Andri...

Alan.hsiang
2019/04/05
0
0
Kotlin入门(26)数据库ManagedSQLiteOpenHelper

共享参数毕竟只能存储简单的键值对数据,如果需要存取更复杂的关系型数据,就要用到数据库SQLite了。尽管SQLite只是手机上的轻量级数据库,但它麻雀虽小、五脏俱全,与Oracle一样存在数据库的...

aqi00
2018/10/19
0
0
不会点SQLite,都不好意思说自己是开发的

一、为什么要会点SQLite? SQLite作为一款轻量级的关系型数据库,占用的资源特别少,所以其应用场景也是特别的多。在移动开发中,我们经常会有将数据存储在本地的需求,此时SQLite将是我们最...

silencezwm
2018/07/03
0
0
高性能Sqlite存储模型对象解密

前言 首先写这篇文章之前祝大家元旦快乐,然后自我介绍一下,我叫吴海超(WHC)在iOS领域有丰富的开发架构经验Github以后我也会以文章的形式分享具有实战意义的文章给大家,希望能够给大家有所...

WHC
2018/10/30
0
0
Android核心技术Intent和数据存储篇

女孩:上海站到了? 男孩:嗯呢?走向世界~ 女孩:Intent核心技术和数据存储技术? 男孩:对,今日就讲这个~ Intent是各个组件之间用来进行通信的,Intent的翻译为“意图”的意思,是传输数据...

达叔小生
2018/07/29
0
0

没有更多内容

加载失败,请刷新页面

加载更多

如何获取当前正在执行的文件的路径和名称?

我有调用其他脚本文件的脚本,但是我需要获取进程中当前正在运行的文件的文件路径。 例如,假设我有三个文件。 使用execfile : script_1.py调用script_2.py 。 反过来, script_2.py调用scr...

技术盛宴
29分钟前
32
0
CSS字体边框?

随着所有新的CSS3边框填充( -webkit ,...),现在是否可以为字体添加边框? (就像蓝色的Twitter徽标周围的纯白色边框一样)。 如果不是,是否有任何不太丑陋的骇客会在CSS / XHTML中完成此...

javail
44分钟前
48
0
Hive安装

下载上传apache-hive-2.1.1-bin.tar.gz文件并解压 tar -zxvf apache-hive-2.1.1-bin.tar.gz -C /export/servers 配置环境变量 vi /etc/profileexport HIVE_HOME=/export/servers/apache......

长臂猿猴
今天
55
0
Fedora 31 - 荣耀魔法本问题记录

最近荣耀魔法本装了Fedora31系统,没有像Deepin 15.11那样出现亮度不能调节和网卡不能用的问题。但是也有不少小问题: 触摸板有时启动后失效,需要重启。 触摸板的右键失效。 待机后进入桌面...

wffger
今天
46
0
ElasticSearch深入:内部机制浅析(三)@

前言 上篇从分布式的角度阐述了 ES 的分布式设计和思想,这一篇打算与 Lucene 结合起来,摸透一些 ES 的常遇到的概念,我们可以将了解到的这些东西应用到优化实践中去。 一、Shard Shard 实际...

HLee
今天
42
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部