关于C#的sqlite数据库操作类

项目需要,用C#编写了一个sqlite的操作类,特此记录一下。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Windows.Forms;
using System.IO;

namespace AutoUpdater_Client.DB
{
    class DBOperator
    {
        //数据库连接
        SQLiteConnection m_dbConnection;
        //要打开或者新建的sqlite数据库文件名
        string dbFileName = string.Empty;

        public DBOperator(string filename)
        {
            this.dbFileName = filename;
        }

        //创建一个空的数据库
        void createNewDatabase()
        {
            try
            {
                FileInfo file = new FileInfo(dbFileName);
                if(!file.Exists)
                    SQLiteConnection.CreateFile(dbFileName);
            }
            catch (Exception)
            {
                throw;
            }
        }

        //创建一个连接到指定数据库
        void openConnection()
        {
            try
            {
                m_dbConnection = null;
                m_dbConnection = new SQLiteConnection("Data Source=" + dbFileName + ";Version=3;");
                m_dbConnection.Open();
            }
            catch (Exception)
            {
                throw;
            }
        }

        //关闭连接
        void closeConnection()
        {
            try
            {
                m_dbConnection.Close();
                m_dbConnection = null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        //执行指定SQL
        public void executeSql(string sql)
        {
            try
            {
                openConnection();
                SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                command.ExecuteNonQuery();
                closeConnection();
            }
            catch (Exception)
            {
                throw;
            }
        }

        //查询特定字段结果
        //参数说明:sql为需要执行的sql脚本,col为要查询的字段名
        public string getSqlResult(string sql, string col)
        {
            string result = string.Empty;
            try
            {
                openConnection();
                SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                SQLiteDataReader reader = command.ExecuteReader();
                while (reader.Read())
                    result = reader[col].ToString();
                closeConnection();
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}

具体的函数使用方法请参考上面代码中的注释。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值