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

来源:互联网 发布:库存整理软件 编辑:程序博客网 时间:2024/05/17 06:55

项目需要,用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;            }        }    }}

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

0 0
原创粉丝点击