C#使用 SQLite 数据库 开发的配置过程及基本操作类,实例程序:工商银行贵金属行情查看小工具

--首发于博客园, 转载请保留此链接  博客原文地址

本文运行环境: Win7 X64, VS2010

1. SQLite 的优点:

    SQLite 是一款轻型数据库,开发包只有十几M, 相对于 MSSQL 几个 G 的体积来说简直是小 Case, 而且在打包成的软件里只需要添加相关的 DLL 就可以在其他的电脑运行,这一点来说比 Access 数据库还要来得方便。

  SQLite虽然很小巧,但是支持的SQL语句不会太逊色于其他开源数据库。

    更多详情参见百科:SQLite

2. 开发包下载

    SQLite 官方下载网址

    本文所用开发包:sqlite-netFx40-setup-bundle-x86-2010-1.0.93.0.exe 

3. VS 2010 使用 SQLite

3.1 安装 SQLite

     3.1.1. 安装部件有3个选项:Full installation(完全安装), Compact installation(精简安装), Custom installation(自定义安装), 本文所选为 Full installation

     3.1.2 默认为不勾选 Instatll the designer components for Visual Studio 2010, 可以把这个选上

 

3.1.2 先在本地创建一个空白文件,扩展名为*.db,

         添加 SQLite 连接: Server Explorer -> Data Connections -> Add Connection ...

         Data Source 为 SQLite Database file

         由于表结构一般是一次性创作,所以添加数据库后使用视图直接建立数据表结构,不必使用代码创建

3.1.3 添加 SQLite 引用

        Solution Explorer -> Reference -> Add Reference...        找到SQLite 安装路径添加 System.Data.SQLite.dll 引用 

        该类库包含SQLiteConnection , SQLiteCommand,SQLiteDataAdapter 等连接操作数据库需要的类

3.1.4 新建 SQLiteHelper 类,主要是db 连接的基本信息,如路径,以及一些数据表的基本操作方法(根据个人需要):


    public class SQLiteHelper
    {
        public SQLiteConnection Connection
        {
            get
            {
                if (_cn == null)
                {
                    Settings settings = new Settings();
                    string connection = settings.Connection.ToString();
                    _cn = new SQLiteConnection(connection);
                }
                return _cn;
            }
        }

        private SQLiteConnection _cn = null;

        public DataTable GetDataTable(string query)
        {
            DataTable dt = new DataTable();
            try
            {
                Connection.Open();
                GetAdapter(query).Fill(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Connection.Close();
            }
            return dt;
        }

        public bool Update(string tableName, DataTable dt)
        {
            try
            {
                Connection.Open();
                string tableStructureQuery = string.Format("SELECT * FROM {0} WHERE 1 = 0", tableName);
                SQLiteDataAdapter da = GetAdapter(tableStructureQuery);
                da.Update(dt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Connection.Close();
            }
            return true;
        }

        public SQLiteDataAdapter GetAdapter(string query)
        {
            SQLiteCommand selectCommand = new SQLiteCommand(query, Connection);
            SQLiteDataAdapter adapter = new SQLiteDataAdapter(selectCommand);
            SQLiteCommandBuilder sb = new SQLiteCommandBuilder(adapter);
            return adapter;
        }

        public bool ExecuteScript(string query)
        {
            try
            {
                SQLiteCommand selectCommand = new SQLiteCommand(query, Connection);
                Connection.Open();
                selectCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                Connection.Close();
            }

            return true;
        }
    }

    public static class DataViewHelper
    {
        public static DataView Clone(this DataView source, string filter)
        {
            if (source == null)
            {
                throw new ApplicationException("Source cannot be null");
            }

            DataView newView = new DataView(source.Table);

            string viewfilter = source.RowFilter;

            List<string> filters = new List<string>();
            if (!string.IsNullOrEmpty(viewfilter))
                filters.Add(string.Format("({0})", viewfilter));
            if (!string.IsNullOrEmpty(filter))
                filters.Add(string.Format("({0})", filter));

            newView.RowFilter = string.Join(" AND ", filters.ToArray());

            return newView;
        }

        public static DataView Clone(this DataView source)
        {
            return source.Clone(string.Empty);
        }
    }

 

(1) 其中 Setting.Connection 为 string 类型,只需要指定 db 路径,本文 Connection 为: Data Source=D:\Trade\Trade\DB\Quotation.db 

      这里提一下 MSSQL 的 连接字符串以示比较,一般情况下 MSSQL 的连接为ConnectionString 类型的配置节点,如:

      <add name="Test" connectionString="Data Source=ServerName;Initial Catalog=dbName;User ID=xxx;Password=***;"
      providerName="System.Data.SqlClient" />

(2) 可以看到数库表的操作方法 与 其他数据库操作 类似:连接,运行操作命令,关闭

(3) 笔者尝试添加一个 SQLiteParameter.Direction 为 ParameterDirection.Output 的参数 但报错,至今没找到正确的使用方法

(4) 使用 SQLiteConnection 可以用 using 的方式使用,有利于程序内存管理及垃圾回收

3.1.5 新建 DAO 类,继承 SQLiteHelper ,主要是针对具体表 的方法: 

 

    public class DAO : SQLiteHelper
    {
        public DAO(string tableName)
        {
            TableName = tableName;
        }
        public string SelectTableQuery { get { return "SELECT * FROM " + TableName; } }

        public string TableStructureQuery { get { return SelectTableQuery + " WHERE 1=0"; } }

        public int GetMaxID(string fieldName)
        {
            StringBuilder commandText = new StringBuilder();
            commandText.AppendLine(string.Format(@"SELECT MAX({0}) ", fieldName));
            commandText.AppendLine(string.Format(@" FROM {0} ", TableName));
            DataTable dt = GetDataTable(commandText.ToString());
            if (dt == null || dt.Rows.Count == 0)
                return 0;
            else
                return int.Parse(dt.Rows[0][0].ToString());
        }

        public string TableName { get; set; }

        internal DataTable GetDataTableStructor()
        {
            return GetDataTable(TableStructureQuery);
        }

        public bool Update(DataTable dt)
        {
            return base.Update(TableName, dt);
        }
    }

 

4. SQLite 实例小程序 

    Quotation 小程序是用于查看工商银行贵金属报价的小工具(这里只更新纸黄金报价),工行贵金属报价官方网址

    用户可以随时查看报价,设置 更新频率(默认更新周期为 120 s )。

    下载的报价数据保存到 quotation.db 里,同时用户可以上传个人贵金属账户交易记录。

    根据交易记录设置个人买卖差价,选择是否播放音乐提醒用户买入卖出,适用于贵金属短线投资辅助小工具(投资有风险,入市需谨慎)

 

4.1 使用方法:

4.1.1 下载:Quotation  Setup 和 db 文件 ( setup 文件用 VS 自带工具打包好的MSI 文件 非源代码 )

4.1.2 安装 Setup 文件, PS: 想要了解 db 结构的读者可以用 VS 或其他 SQLite 命令、视图软件查看

4.1.3 更改配置文件,打开 Trade.exe.config , 修改 节点:

<setting name="Connection" serializeAs="String">
<value>Data Source=D:\Trade\Trade\DB\Quotation.db</value>
</setting>

        其中 <value>Data Source = db path</value> 是 Quotation.db 的存放路径,注意如果软件安装在 C 盘保存时可能提示无法访问,这时可以把 .config 文件复制出来修改后再替换原来的文件

4.1.4 从 <Load Trx> 菜单命令导入从工行下载好的 txt 文件(不要更改格式)用于比较差价, <Transactions> 查看导入的交易记录,无效的交易记录可以选中后 Transactions -> Close 来关闭记录。

4.1.5 小程序为笔者个人开发,用于学习交流,个人免费使用,著作权解释权归软件作者所有,任何人不得进行反编译及以此向他人收取任何费用,欢迎读者留言提出意见和建议。

4.1.6 程序截图

 

 

补充:

android app 查询工行报价可到以下网址下载:

IcbcQuotation 下载 http://pan.baidu.com/s/1mgFsu2c#path=%252FAndroid%2520App%2520Release

软件说明: 其实是报价网址的快捷方式,只是每隔30s 自动刷新一下

软件截图:

posted @ 2014-07-21 00:43  沐汐Vicky  阅读(3325)  评论(7编辑  收藏  举报