一、System.Data.SQLite
1. 下载安装
下载地址:https://system.data.sqlite.org/index.html/doc/trunk/www/downloads-unsup.wiki。
这里我使用的是.NET 4.0,所以下载64位 for 4.0 的支持:
 
 下载之后安装:
 
 安装完成之后查看安装目录:
 
2. 添加引用库到工程

 
二、使用
1. 引用
using System.Data.SQLite;
 
2. 连接到指定数据库
先设计一个简单的界面:
 
 然后编写load按钮的回调函数:
namespace Demo_SQLite3
{
    public partial class Form1 : Form
    {
        // 数据库连接
        SQLiteConnection s_dbConnection;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            // 弹出文件选择框供用户选择
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择要加载的文件(DB格式)";
            dialog.Filter = "db文件(*.db)|*.db";
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            // 显示用户选择的文件路径
            string file = dialog.FileName;
            // 获取文件名
            string filename = Path.GetFileName(file);
            textBox2.AppendText("尝试打开数据库" + filename + "..." + Environment.NewLine);
            // 路径标识符转义
            file = file.Replace("\\", "\\\\");
            textBox1.AppendText(file);
            // 创建数据库连接
            s_dbConnection = new SQLiteConnection("Data Source="+ file); //没有数据库则会自动创建
            try
            {
                // 打开数据库
                s_dbConnection.Open();
                textBox2.AppendText("打开成功!" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                textBox2.AppendText("打开发生异常: " + ex.ToString() + Environment.NewLine);
            }
        }
    }
}
 
运行,加载一个之前手动创建的数据库:
 
3. 执行数据库命令(有结果)
编写查询全部按钮的回调函数,执行查询数据库的命令:
private void button2_Click(object sender, EventArgs e)
{
   string sql = "select * from class1";
   SQLiteCommand command = new SQLiteCommand(sql, s_dbConnection);
   SQLiteDataReader reader = command.ExecuteReader();
   while (reader.Read())
       textBox2.AppendText("ID: " + reader["ID"] + "Name: " + reader["name"] + "Age: " + reader["AGE"] + Environment.NewLine);
}
 
运行结果如下:
 










