c#操作sqlite实现数据的增删改查-kb88凯时官网登录

来自:网络
时间:2023-01-01
阅读:
免费资源网 - https://freexyz.cn/
目录

简介

sqlite是一个轻量级、跨平台的关系型数据库,在小型项目中,方便,易用,同时支持多种开发语言,下面是我用c#语言对sqlite 的一个封装。

winfrom界面如下:

代码还需要改进部分:

下面的代码我不觉得是完美的,读者可以自己去实现这些功能:

1.如果不想用多线程可以去掉usinglock.cs ,在sqlitehelper.cs中删除对应的引用即可。

2.创建数据库文件,可以从代码中分离成单独的方法。比如创建有密码的数据库文件。

3.在执行sql语句时,有些语句执行成功,也不会有影响行数。比如,创建表,删除表,此时执行sql语句返回的影响行数就为0。

4.只要sql语句不报错就是执行成功的,在方法的返回值可以改为多个,比如用 

tuple 第一个参数 bool 代表执行结果,第二个参数 string 代表错误信息,第三个参数 int 代表影响的行数。

同样,也可以这样:

tuple 第一个参数 bool 代表执行结果,第二个参数 string 代表错误信息,第三个参数 dataset 代表返回的表单数据。

主要代码

sqlitehelper.cs

using system;
using system.collections.generic;
using system.data;
using system.data.common;
using system.data.sqlite;
using system.io;
using system.text;
 
namespace mysqlitehelper
{
    public class sqlitehelper
    {
        #region 字段
        
        /// 
        /// 事务的基类
        /// 
        private dbtransaction dbtrans;
        /// 
        /// 使用静态变量字典解决多线程实例本类,实现一个数据库对应一个clslock
        /// 
        private static readonly dictionary rwl = new dictionary();
        /// 
        /// 数据库地址
        /// 
        private readonly string mdatafile;
        /// 
        /// 数据库密码
        /// 
        private readonly string mpassword;
        private readonly string lockname = null;
        /// 
        /// 数据库连接定义
        /// 
        private sqliteconnection mconn;
 
        #endregion
 
        #region 构造函数
 
        /// 
        /// 根据数据库地址初始化
        /// 
        /// 数据库地址
        public sqlitehelper(string datafile)
        {
            this.mdatafile = datafile ?? throw new argumentnullexception("datafile=null");
            //this.mdatafile = appdomain.currentdomain.basedirectory   datafile;
            this.mdatafile = datafile;
            if (!rwl.containskey(datafile))
            {
                lockname = datafile;
                rwl.add(datafile, new clslock());
            }
        }
 
        /// 
        /// 使用密码打开数据库
        /// 
        /// 数据库地址
        /// 数据库密码
        public sqlitehelper(string datafile, string password)
        {
            this.mdatafile = datafile ?? throw new argumentnullexception("datafile is null");
            this.mpassword = password ?? throw new argumentnullexception("password is null");
            //this.mdatafile = appdomain.currentdomain.basedirectory   datafile;
            this.mdatafile = datafile;
            if (!rwl.containskey(datafile))
            {
                lockname = datafile;
                rwl.add(datafile, new clslock());
            }
        }
 
        #endregion
 
        #region 打开/关闭 数据库
 
        ///   
        /// 打开 sqlitemanager 使用的数据库连接  
        ///   
        public void open()
        {
            if (string.isnullorwhitespace(mpassword))
            {
                mconn = openconnection(this.mdatafile);
            }
            else
            {
                mconn = openconnection(this.mdatafile, mpassword);
            }
            console.writeline("打开数据库成功");
        }
 
        /// 
        /// 关闭连接
        /// 
        public void close()
        {
            if (this.mconn != null)
            {
                try
                {
                    this.mconn.close();
                    if (rwl.containskey(lockname))
                    {
                        rwl.remove(lockname);
                    }
                }
                catch
                {
                    console.writeline("关闭失败");
                }
            }
            console.writeline("关闭数据库成功");
        }
 
        #endregion
 
        #region 事务
 
        /// 
        /// 开始事务
        /// 
        public void begintrain()
        {
            ensureconnection();
            dbtrans = mconn.begintransaction();
        }
 
        /// 
        /// 提交事务
        /// 
        public void dbcommit()
        {
            try
            {
                dbtrans.commit();
            }
            catch (exception)
            {
                dbtrans.rollback();
            }
        }
 
        #endregion
 
        #region 工具
 
        ///   
        /// 打开一个sqlite数据库文件,如果文件不存在,则创建(无密码)
        ///   
        ///   
        /// sqliteconnection 类  
        private sqliteconnection openconnection(string datafile)
        {
            if (datafile == null)
            {
                throw new argumentnullexception("datafiledatafile=null");
            }
            if (!file.exists(datafile))
            {
                sqliteconnection.createfile(datafile);
            }
            sqliteconnection conn = new sqliteconnection();
            sqliteconnectionstringbuilder constr = new sqliteconnectionstringbuilder
            {
                datasource = datafile
            };
            conn.connectionstring = constr.tostring();
            conn.open();
            return conn;
        }
 
        ///   
        /// 打开一个sqlite数据库文件,如果文件不存在,则创建(有密码)
        ///   
        ///   
        /// 
        /// sqliteconnection 类  
        private sqliteconnection openconnection(string datafile, string password)
        {
            if (datafile == null)
            {
                throw new argumentnullexception("datafile=null");
            }
            if (!file.exists(convert.tostring(datafile)))
            {
                sqliteconnection.createfile(datafile);
            }
            try
            {
                sqliteconnection conn = new sqliteconnection();
                sqliteconnectionstringbuilder constr = new sqliteconnectionstringbuilder
                {
                    datasource = datafile,
                    password = password
                };
                conn.connectionstring = constr.tostring();
                conn.open();
                return conn;
            }
            catch (exception)
            {
                return null;
            }
        }
 
        ///   
        /// 读取 或 设置 sqlitemanager 使用的数据库连接  
        ///   
        public sqliteconnection connection
        {
            get
            {
                return mconn;
            }
            private set
            {
                mconn = value ?? throw new argumentnullexception();
            }
        }
 
        /// 
        /// 确保数据库是连接状态
        /// 
        /// 
        protected void ensureconnection()
        {
            if (this.mconn == null)
            {
                throw new exception("sqlitemanager.connection=null");
            }
            if (mconn.state != connectionstate.open)
            {
                mconn.open();
            }
        }
 
        /// 
        /// 获取数据库文件的路径
        /// 
        /// 
        public string getdatafile()
        {
            return this.mdatafile;
        }
 
        ///   
        /// 判断表 table 是否存在  
        ///   
        ///   
        /// 存在返回true,否则返回false  
        public bool tableexists(string table)
        {
            if (table == null)
            {
                throw new argumentnullexception("table=null");
            }
            ensureconnection();
            sqlitedatareader reader = executereader("select count(*) as c from sqlite_master where type='table' and name=@tablename ", new sqliteparameter[] { new sqliteparameter("tablename", table) });
            if (reader == null)
            {
                return false;
            }
            reader.read();
            int c = reader.getint32(0);
            reader.close();
            reader.dispose();
            //return false;  
            return c == 1;
        }
 
        /// 
        /// vacuum 命令(通过复制主数据库中的内容到一个临时数据库文件,然后清空主数据库,并从副本中重新载入原始的数据库文件)
        /// 
        /// 
        public bool vacuum()
        {
            try
            {
                using (sqlitecommand command = new sqlitecommand("vacuum", connection))
                {
                    command.executenonquery();
                }
                return true;
            }
            catch (system.data.sqlite.sqliteexception)
            {
                return false;
            }
        } 
 
        #endregion
 
        #region 执行sql
 
        /// 
        /// 执行sql, 并返回 sqlitedatareader 对象结果 
        ///   
        /// 
        /// null 表示无参数
        ///   
        public sqlitedatareader executereader(string sql, sqliteparameter[] paramarr)
        {
            if (sql == null)
            {
                throw new argumentnullexception("sql=null");
            }
            ensureconnection();
            using (rwl[lockname].read())
            {
                using (sqlitecommand cmd = new sqlitecommand(sql, connection))
                {
                    if (paramarr != null)
                    {
                        cmd.parameters.addrange(paramarr);
                    }
                    try
                    {
                        sqlitedatareader reader = cmd.executereader();
                        cmd.parameters.clear();
                        return reader;
                    }
                    catch (exception)
                    {
                        return null;
                    }
                }
            }
        }
 
        /// 
        /// 执行查询,并返回dataset对象
        /// 
        /// sql查询语句
        /// 参数数组
        /// 
        public dataset executedataset(string sql, sqliteparameter[] paramarr)
        {
            if (sql == null)
            {
                throw new argumentnullexception("sql=null");
            }
            this.ensureconnection();
            using (rwl[lockname].read())
            {
                using (sqlitecommand cmd = new sqlitecommand(sql, this.connection))
                {
                    if (paramarr != null)
                    {
                        cmd.parameters.addrange(paramarr);
                    }
                    try
                    {
                        sqlitedataadapter da = new sqlitedataadapter();
                        dataset ds = new dataset();
                        da.selectcommand = cmd;
                        da.fill(ds);
                        cmd.parameters.clear();
                        da.dispose();
                        return ds;
                    }
                    catch (exception)
                    {
                        return null;
                    }
                }
            }
        }
 
        /// 
        /// 执行sql查询,并返回dataset对象。
        /// 
        /// 映射源表的名称
        /// sql语句
        /// sql参数数组
        /// 
        public dataset executedataset(string strtable, string sql, sqliteparameter[] paramarr)
        {
            if (sql == null)
            {
                throw new argumentnullexception("sql=null");
            }
            this.ensureconnection();
            using (rwl[lockname].read())
            {
                using (sqlitecommand cmd = new sqlitecommand(sql, this.connection))
                {
                    if (paramarr != null)
                    {
                        cmd.parameters.addrange(paramarr);
                    }
                    try
                    {
                        sqlitedataadapter da = new sqlitedataadapter();
                        dataset ds = new dataset();
                        da.selectcommand = cmd;
                        da.fill(ds, strtable);
                        cmd.parameters.clear();
                        da.dispose();
                        return ds;
                    }
                    catch (exception)
                    {
                        return null;
                    }
                }
            }
        }
 
        ///   
        /// 执行sql,返回受影响的行数,可用于执行表创建语句,paramarr == null 表示无参数
        ///   
        ///   
        ///   
        public int executenonquery(string sql, sqliteparameter[] paramarr)
        {
            if (sql == null)
            {
                throw new argumentnullexception("sql=null");
            }
            this.ensureconnection();
            using (rwl[lockname].read())
            {
                try
                {
                    using (sqlitecommand cmd = new sqlitecommand(sql, connection))
                    {
                        if (paramarr != null)
                        {
                            foreach (sqliteparameter p in paramarr)
                            {
                                cmd.parameters.add(p);
                            }
                        }
                        int c = cmd.executenonquery();
                        cmd.parameters.clear();
                        return c;
                    }
                }
                catch (sqliteexception)
                {
                    return 0;
                }
            }
        }
 
        ///   
        /// 执行sql,返回结果集第一行,如果结果集为空,那么返回空 list(list.count=0), 
        /// rowwrapper = null 时,使用 wraprowtodictionary  
        ///   
        ///   
        ///   
        ///   
        public object executescalar(string sql, sqliteparameter[] paramarr)
        {
            if (sql == null)
            {
                throw new argumentnullexception("sql=null");
            }
            this.ensureconnection();
            using (rwl[lockname].read())
            {
                using (sqlitecommand cmd = new sqlitecommand(sql, connection))
                {
                    if (paramarr != null)
                    {
                        cmd.parameters.addrange(paramarr);
                    }
                    try
                    {
                        object reader = cmd.executescalar();
                        cmd.parameters.clear();
                        cmd.dispose();
                        return reader;
                    }
                    catch (exception)
                    {
                        return null;
                    }
                }
            }
        }
 
        ///   
        /// 查询一行记录,无结果时返回 null,conditioncol = null 时将忽略条件,直接执行 select * from table   
        ///   
        /// 表名  
        ///   
        ///   
        ///   
        public object queryone(string table, string conditioncol, object conditionval)
        {
            if (table == null)
            {
                throw new argumentnullexception("table=null");
            }
            this.ensureconnection();
            string sql = "select * from "   table;
            if (conditioncol != null)
            {
                sql  = " where "   conditioncol   "=@"   conditioncol;
            }
            object result = executescalar(sql, new sqliteparameter[] { new sqliteparameter(conditioncol, conditionval) });
            return result;
        }
 
        #endregion
 
        #region 增 删 改
 
        ///   
        /// 执行 insert into 语句 
        ///   
        ///   
        ///   
        ///   
        public int insertdata(string table, dictionary entity)
        {
            if (table == null)
            {
                throw new argumentnullexception("table=null");
            }
            this.ensureconnection();
            string sql = buildinsert(table, entity);
            return this.executenonquery(sql, buildparamarray(entity));
        }
 
        ///   
        /// 执行 update 语句,注意:如果 where = null,那么 whereparams 也为 null,
        ///   
        /// 表名  
        /// 要修改的列名和列名的值  
        /// 查找符合条件的列  
        /// where条件中参数的值  
        ///   
        public int update(string table, dictionary entity, string where, sqliteparameter[] whereparams)
        {
            if (table == null)
            {
                throw new argumentnullexception("table=null");
            }
            this.ensureconnection();
            string sql = buildupdate(table, entity);
            sqliteparameter[] parameter = buildparamarray(entity);
            if (where != null)
            {
                sql  = " where "   where;
                if (whereparams != null)
                {
                    sqliteparameter[] newarr = new sqliteparameter[(parameter.length   whereparams.length)];
                    array.copy(parameter, newarr, parameter.length);
                    array.copy(whereparams, 0, newarr, parameter.length, whereparams.length);
                    parameter = newarr;
                }
            }
            return this.executenonquery(sql, parameter);
        }
 
        ///   
        /// 执行 delete from table 语句,where不必包含'where'关键字,where = null 时将忽略 whereparams  
        ///   
        ///   
        ///   
        ///   
        ///   
        public int delete(string table, string where, sqliteparameter[] whereparams)
        {
            if (table == null)
            {
                throw new argumentnullexception("table=null");
            }
            this.ensureconnection();
            string sql = "delete from "   table   " ";
            if (where != null)
            {
                sql  = "where "   where;
            }
            return executenonquery(sql, whereparams);
        }
 
        /// 
        /// 将 dictionary 类型数据 转换为 sqliteparameter[] 类型
        /// 
        /// 
        /// 
        private sqliteparameter[] buildparamarray(dictionary entity)
        {
            list list = new list();
            foreach (string key in entity.keys)
            {
                list.add(new sqliteparameter(key, entity[key]));
            }
            if (list.count == 0)
            {
                return null;
            }
            return list.toarray();
        }
 
        /// 
        /// 将 dictionary 类型数据 转换为 插入数据 的 sql语句
        /// 
        /// 表名
        /// 字典
        /// 
        private string buildinsert(string table, dictionary entity)
        {
            stringbuilder buf = new stringbuilder();
            buf.append("insert into ").append(table);
            buf.append(" (");
            foreach (string key in entity.keys)
            {
                buf.append(key).append(",");
            }
            buf.remove(buf.length - 1, 1); // 移除最后一个,
            buf.append(") ");
            buf.append("values(");
            foreach (string key in entity.keys)
            {
                buf.append("@").append(key).append(","); // 创建一个参数
            }
            buf.remove(buf.length - 1, 1);
            buf.append(") ");
 
            return buf.tostring();
        }
 
        /// 
        /// 将 dictionary 类型数据 转换为 修改数据 的 sql语句
        /// 
        /// 表名
        /// 字典
        /// 
        private string buildupdate(string table, dictionary entity)
        {
            stringbuilder buf = new stringbuilder();
            buf.append("update ").append(table).append(" set ");
            foreach (string key in entity.keys)
            {
                buf.append(key).append("=").append("@").append(key).append(",");
            }
            buf.remove(buf.length - 1, 1);
            buf.append(" ");
            return buf.tostring();
        }
 
        #endregion
    }
}

usinglock.cs

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.threading;
 
namespace mysqlitehelper
{
    /// 
    /// 使用using代替lock操作的对象,可指定写入和读取锁定模式
    /// 
    public sealed class clslock
    {
        #region 内部类
 
        /// 
        /// 利用idisposable的using语法糖方便的释放锁定操作内部类
        /// 
        private struct lock : idisposable
        {
            /// 
            /// 读写锁对象
            /// 
            private readonly readerwriterlockslim _lock;
            /// 
            /// 是否为写入模式
            /// 
            private bool _iswrite;
            /// 
            /// 利用idisposable的using语法糖方便的释放锁定操作构造函数
            /// 
            /// 读写锁
            /// 写入模式为true,读取模式为false
            public lock(readerwriterlockslim rwl, bool iswrite)
            {
                _lock = rwl;
                _iswrite = iswrite;
            }
            /// 
            /// 释放对象时退出指定锁定模式
            /// 
            public void dispose()
            {
                if (_iswrite)
                {
                    if (_lock.iswritelockheld)
                    {
                        _lock.exitwritelock();
                    }
                }
                else
                {
                    if (_lock.isreadlockheld)
                    {
                        _lock.exitreadlock();
                    }
                }
            }
        }
 
        /// 
        /// 空的可释放对象,免去了调用时需要判断是否为null的问题内部类
        /// 
        private class disposable : idisposable
        {
            /// 
            /// 空的可释放对象
            /// 
            public static readonly disposable empty = new disposable();
            /// 
            /// 空的释放方法
            /// 
            public void dispose() { }
        }
 
        #endregion
 
        /// 
        /// 读写锁
        /// 
        private readonly readerwriterlockslim _lockslim = new readerwriterlockslim();
        /// 
        /// 使用using代替lock操作的对象,可指定写入和读取锁定模式构造函数
        /// 
        public clslock()
        {
            enabled = true;
        }
        /// 
        /// 是否启用,当该值为false时,read()和write()方法将返回 disposable.empty
        /// 
        public bool enabled { get; set; }
 
        ///  
        /// 进入读取锁定模式,该模式下允许多个读操作同时进行,
        /// 退出读锁请将返回对象释放,建议使用using语块,
        /// enabled为false时,返回disposable.empty,
        /// 在读取或写入锁定模式下重复执行,返回disposable.empty;
        /// 
        public idisposable read()
        {
            if (enabled == false || _lockslim.isreadlockheld || _lockslim.iswritelockheld)
            {
                return disposable.empty;
            }
            else
            {
                _lockslim.enterreadlock();
                return new lock(_lockslim, false);
            }
        }
 
        ///  
        /// 进入写入锁定模式,该模式下只允许同时执行一个读操作,
        /// 退出读锁请将返回对象释放,建议使用using语块,
        /// enabled为false时,返回disposable.empty,
        /// 在写入锁定模式下重复执行,返回disposable.empty
        /// 
        /// 读取模式下不能进入写入锁定状态
        public idisposable write()
        {
            if (enabled == false || _lockslim.iswritelockheld)
            {
                return disposable.empty;
            }
            else if (_lockslim.isreadlockheld)
            {
                throw new notimplementedexception("读取模式下不能进入写入锁定状态");
            }
            else
            {
                _lockslim.enterwritelock();
                return new lock(_lockslim, true);
            }
        }
    }
 
}

form1.cs

using mysqlitehelper;
using system;
using system.collections.generic;
using system.data;
using system.data.sqlite;
using system.windows.forms;
 
namespace sqlitedemo
{
    public partial class form1 : form
    {
        public form1()
        {
            initializecomponent();
        }
 
        private sqlitehelper sqlitehelpers = null;
        private const string dbaddress = "d:\\sqlitedata\\test_record.db3";
 
        private void form1_load(object sender, eventargs e)
        {
            sqlitehelpers = new sqlitehelper(dbaddress,"123456");
        }
 
        /// 
        /// 打开数据库
        /// 
        /// 
        /// 
        private void button_opendb_click(object sender, eventargs e)
        {
            sqlitehelpers.open();
            label_dbopenstate.text = "打开";
        }
 
        /// 
        /// 关闭数据库
        /// 
        /// 
        /// 
        private void button_closedb_click(object sender, eventargs e)
        {
            sqlitehelpers.close();
            label_dbopenstate.text = "关闭";
        }
 
        /// 
        /// 查询
        /// 
        /// 
        /// 
        private void button_query_click(object sender, eventargs e)
        {
            sqliteparameter[] parameter = new sqliteparameter[]
            {
                new sqliteparameter("address", "济南")
            };
            string sql = "select * from student where address = @address";
            dataset dataset = sqlitehelpers.executedataset(sql, parameter);
            if (dataset != null)
            {
                datagridview1.datasource = dataset.tables[0];
            }
        }
 
        /// 
        /// 插入数据
        /// 
        /// 
        /// 
        private void button_add_click(object sender, eventargs e)
        {
            dictionary dic = new dictionary();
            dic.add("id", 6);
            dic.add("name", "王二麻子");
            dic.add("age", 44);
            dic.add("address", "陕西");
 
            int result = sqlitehelpers.insertdata("student", dic);
            console.writeline("插入结果,受影响的行数:"   result);
        }
 
        /// 
        /// 修改数据
        /// 
        /// 
        /// 
        private void button_modify_click(object sender, eventargs e)
        {
            dictionary dic = new dictionary();
            //将列名 name 的值改为 “猴子”
            dic.add("name", "猴子");
            //将列名 address 的值改为 花果山
            dic.add("address", "花果山");
            //where条件
            string where = "id = @id and age = @age";
            //where条件中对应的参数
            sqliteparameter[] parameter = new sqliteparameter[]
            {
                new sqliteparameter("id", 4),
                new sqliteparameter("age",23)
            };
            
            int result = sqlitehelpers.update("student", dic, where, parameter);
            console.writeline("修改结果,受影响的行数:"   result);
        }
 
        /// 
        /// 删除数据
        /// 
        /// 
        /// 
        private void button_delete_click(object sender, eventargs e)
        {
            //where条件
            string where = "id = @id";
            //where条件中对应的参数
            sqliteparameter[] parameter = new sqliteparameter[]
            {
                new sqliteparameter("id", 6),
            };
 
            int result = sqlitehelpers.delete("student", where, parameter);
            console.writeline("删除结果,受影响的行数:"   result);
        }
 
        /// 
        /// 判断表是否存在
        /// 
        /// 
        /// 
        private void button_tableexists_click(object sender, eventargs e)
        {
            string title = "dddd";
            bool result = sqlitehelpers.tableexists(title);
            console.writeline(string.format("{0} 表是否存在,结果:{1}", title, result));
        }
 
        //输出各表中的数据
        //public static void printvalues(dataset ds)
        //{
        //    foreach (datatable table in ds.tables)
        //    {
        //        console.writeline("表名称:"   table.tablename);
        //        foreach (datarow row in table.rows)
        //        {
        //            foreach (datacolumn column in table.columns)
        //            {
        //                console.write(row[column]   "");
        //            }
        //            console.writeline();
        //        }
        //    }
        //}
 
    }
}

以上就是c#操作sqlite实现数据的增删改查的详细内容,更多关于c# sqlite增删改查的资料请关注其它相关文章!

免费资源网 - https://freexyz.cn/
返回顶部
顶部
网站地图