文档章节

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

深圳大道
 深圳大道
发布于 2016/12/29 15:38
字数 1845
阅读 5
收藏 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
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

没有更多内容

加载失败,请刷新页面

加载更多

Linux修改时区的正确方法【修改时间,需要修改软连接,靠谱】

CentOS和Ubuntu的时区文件是/etc/localtime,但是在CentOS7以后localtime以及变成了一个链接文件 [root@centos7 ~]# ll /etc/localtime lrwxrwxrwx 1 root root 33 Oct 12 11:01 /etc/loca......

Airship
28分钟前
0
0
《Netkiller Spring Cloud 手札》之 Master / Slave 主从数据库数据源配置

5.19.1. Master / Slave 主从数据库数据源配置 5.19.1.1. application.properties spring.datasource.master.driverClassName = com.mysql.cj.jdbc.Driverspring.datasource.master.url=j......

netkiller-
32分钟前
36
0
大数据(hadoop-HDFS的本地开发环境的配置与常见的HDFS的JAVA API)

HDFS的本地开发环境搭建 1:所需工具 1)hadoop2.7.3安装包 2)hadoop-eclipse-plugin插件 https://github.com/winghc/hadoop2x-eclipse-plugin 2:搭建过程 1:解压hadoop2.7.3文件2:下载...

这很耳东先生
44分钟前
1
0
TCP协议的定义和丢包时的重传机制

TCP是一个巨复杂的协议,因为他要解决很多问题,而这些问题又带出了很多子问题和阴暗面。所以学习TCP本身是个比较痛苦的过程,但对于学习的过程却能让人有很多收获。关于TCP这个协议的细节,...

tantexian
44分钟前
2
0
图解Tomcat类加载机制(阿里面试题)

Tomcat的类加载机制是违反了双亲委托原则的,对于一些未加载的非基础类(Object,String等),各个web应用自己的类加载器(WebAppClassLoader)会优先加载,加载不到时再交给commonClassLoader走双...

群星纪元
50分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部