【WinForm】杂记(1):C#通过SQLite读取DB(.db)文件

第一步 下载DLL文件并安装

DLL下载地址https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

选用版本sqlite-netFx46-setup-bundle-x64-2015-1.0.112.0.exe,适用框架.NET Framework 4.6(可以根据自己的需要选用)。

下载后,系统默认安装在C:Program FilesSystem.Data.SQLite路径下,拷贝System.Data.SQLite.dll文件到工程文件目录下X:/Project/bin/debug。

在解决方案资源管理器中,选择“引用”,右键后选择“添加引用”

如图1,在引用管理器侧边栏选择“浏览”后,再点击“浏览”按钮,安装之前保存在工程文件目录下的System.Data.SQLite.dll,点击“确定”后完成。

在程序中添加引用后,在程序中添加命名空间,完成第一步

using System.Data.SQLite;  

  

第二步 获取数据

 1 public DataTable GetDataTable(string strSQL, string path){
 2     DataTable dt = null;
 3     try {
 4         SQLiteConnection conn = new SQLiteConnection(path);
 5         SQLiteCommand cmd = new SQLiteCommand(strSQL,conn);
 6         SQLiteDataAdapter reciever = new SQLiteDataAdapter(cmd);
 7         dt = new DataTable();
 8         reciever.Fill(dt);
 9         return dt;
10     } catch{
11         MessageBox.Show("There is no such a datatable");
12     }
13     return dt;
14 }

 其中strSQL是获取db文件中数据表的指令

string sSQL = "SELECT * FROM item_compound;";

这里的数据表名为"item_compound"。

文件路Path

public static string DBPath = string.Format(@"Data Source={0}",  Application.StartupPath + @"CCUS_supstr_temp.db");//the path of .db file

这里的db文件名为“CCUS_supstr_temp.db”。

第三步 测试代码

private void FrmConvert_Load(object sender, EventArgs e){
    string sSQL = "SELECT * FROM item_compound;";
    DataTable dbt = GetDataTable(sSQL, DBPath);
    this.dataGridView1.DataSource = dbt;
}  

结果如图2

原文地址:https://www.cnblogs.com/RicardoIsLearning/p/12103332.html