您的位置:首页 > 博客中心 > 数据库 >

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

时间:2022-03-10 18:07

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

本文运行环境: Win7 X64, VS2010

1. SQLite 的优点:

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

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

    更多详情参见百科:

2. 开发包下载

   

    本文所用开发包: 

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, 可以把这个选上

gxlsystem.com,布布扣

 

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

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

         Data Source 为 SQLite Database file

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

gxlsystem.com,布布扣

gxlsystem.com,布布扣

gxlsystem.com,布布扣

3.1.3 添加 SQLite 引用

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

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

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

  1     public class SQLiteHelper
  2     {
  3         public SQLiteConnection Connection
  4         {
  5             get
  6             {
  7                 if (_cn == null)
  8                 {
  9                     Settings settings = new Settings();
 10                     string connection = settings.Connection.ToString();
 11                     _cn = new SQLiteConnection(connection);
 12                 }
 13                 return _cn;
 14             }
 15         }
 16 
 17         private SQLiteConnection _cn = null;
 18 
 19         public DataTable GetDataTable(string query)
 20         {
 21             DataTable dt = new DataTable();
 22             try
 23             {
 24                 Connection.Open();
 25                 GetAdapter(query).Fill(dt);
 26             }
 27             catch
 28             { }
 29             finally
 30             {
 31                 Connection.Close();
 32             }
 33             return dt;
 34         }
 35 
 36         public bool Update(string tableName, DataTable dt)
 37         {
 38             try
 39             {
 40                 Connection.Open();
 41                 string tableStructureQuery = string.Format("SELECT * FROM {0} WHERE 1 = 0", tableName);
 42                 SQLiteDataAdapter da = GetAdapter(tableStructureQuery);
 43                 da.Update(dt);
 44             }
 45             catch (Exception ex)
 46             {
 47                 MessageBox.Show(ex.Message);
 48             }
 49             finally
 50             {
 51                 Connection.Close();
 52             }
 53             return true;
 54         }
 55 
 56         public SQLiteDataAdapter GetAdapter(string query)
 57         {
 58             SQLiteCommand selectCommand = new SQLiteCommand(query, Connection);
 59             SQLiteDataAdapter adapter = new SQLiteDataAdapter(selectCommand);
 60             SQLiteCommandBuilder sb = new SQLiteCommandBuilder(adapter);
 61             return adapter;
 62         }
 63 
 64         public bool ExecuteScript(string query)
 65         {
 66             try
 67             {
 68                 SQLiteCommand selectCommand = new SQLiteCommand(query, Connection);
 69                 Connection.Open();
 70                 selectCommand.ExecuteNonQuery();
 71             }
 72             catch
 73             {
 74                 return false;
 75             }
 76             finally
 77             {
 78                 Connection.Close();
 79             }
 80 
 81             return true;
 82         }
 83     }
 84 
 85     public static class DataViewHelper
 86     {
 87         public static DataView Clone(this DataView source, string filter)
 88         {
 89             if (source == null)
 90             {
 91                 throw new ApplicationException("Source cannot be null");
 92             }
 93 
 94             DataView newView = new DataView(source.Table);
 95 
 96             string viewfilter = source.RowFilter;
 97 
 98             List<string> filters = new List<string>();
 99             if (!string.IsNullOrEmpty(viewfilter))
100                 filters.Add(string.Format("({0})", viewfilter));
101             if (!string.IsNullOrEmpty(filter))
102                 filters.Add(string.Format("({0})", filter));
103 
104             newView.RowFilter = string.Join(" AND ", filters.ToArray());
105 
106             return newView;
107         }
108 
109         public static DataView Clone(this DataView source)
110         {
111             return source.Clone(string.Empty);
112         }
113     }

(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 ,主要是针对具体表 的方法:

 1    public  class DAO : SQLiteHelper
 2     {
 3         public DAO(string tableName)
 4         {
 5             TableName = tableName;
 6         }
 7         public string SelectTableQuery { get { return "SELECT * FROM " + TableName; } }
 8 
 9          public string TableStructureQuery { get { return SelectTableQuery + " WHERE 1=0"; } }
10 
11          public int GetMaxID(string fieldName)
12          {14              StringBuilder commandText = new StringBuilder();
15              commandText.AppendLine(string.Format(@"SELECT MAX({0}) ", fieldName));
16              commandText.AppendLine(string.Format(@" FROM {0} ", TableName));
17              DataTable dt = GetDataTable(commandText.ToString());
18              if (dt.Rows.Count == 0)
19                  return 0;
20              else
21                  return int.Parse(dt.Rows[0][0].ToString());
22          }
23 
24         public string TableName { get; set; }
25 
26         internal DataTable GetDataTableStructor()
27         {
28             return GetDataTable(TableStructureQuery);
29         }
30 
31         public bool Update(DataTable dt)
32         {
33             return base.Update(TableName, dt);
34         }
35     }

 

4. SQLite 实例小程序 

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

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

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

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

 

4.1 使用方法:

4.1.1 下载: 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 程序截图

gxlsystem.com,布布扣

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

热门排行

今日推荐

热门手游