SQLite
SQLite 是一种小型的关系数据库。相比于 MySQL、SQLServer 这样的客户端/服务器模式,它的存储方式更接近对文件的读写。而相比于普通的文件,SQLite 又支持我们使用 SQL 语句来操纵数据。本文将会简单介绍一下如何在 C# 语言中使用 SQLite。
System.Data.SQLite
在 C# 中操作 SQLite 我们需要使用 System.Data.SQLite 这个类库。这个库并不是 .NET 的标准库,所以我们需要手动下载它。这里给出一个可用的下载链接。
在使用之前,我们需要将 dll 文件拷贝到工程项目中,然后添加对 dll 文件的引用。
基本操作
1.创建数据库文件
SQLiteConnection.CreateFile("sqlite.db");
2.创建和打开数据库连接
SQLiteConnection conn = new SQLiteConnection("Data Source=sqlite.db;Version=3;");
conn.Open();
3.创建表
string sql = "create table employee (name varchar(20), age int)";
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
4.插入数据记录
sql = "insert into employee (name,age) values ('wuzhiyu',25)";
cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
其中 cmd.ExecuteNonQuery();
一般用来执行插入、更新和删除操作。
5.查询数据
sql = "select * from employee";
cmd = new SQLiteCommand(sql, conn);
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine("Name:" + reader["name"] + "\t Age:" + reader["age"]);
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql,conn);
DataTable dt=new DataTable();
int count = adapter.Fill(dt);
for(int i=0;i<count;i++)
{
Console.WriteLine("Name: {0}\t Age: {1}", dt.Rows[i][0], dt.Rows[i][1]);
}
上面给出了两种读取数据的方法,一个是使用类似迭代器(或者说游标)的方法一行行来读取数据记录,第二种则是使用类似适配器的方式将数据填充到 DataTable 中,然后我们对 DataTable 进行操作。
源代码
namespace SQLite
{
class Program
{
static void Main(string[] args)
{
//1. Create a database file
SQLiteConnection.CreateFile("sqlite.db");
//2. Connecting to a database
SQLiteConnection conn = new SQLiteConnection("Data Source=sqlite.db;Version=3;");
conn.Open();
//3. Create a table
string sql = "create table employee (name varchar(20), age int)";
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
//4. Insert records
sql = "insert into employee (name,age) values ('wuzhiyu',25)";
cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
sql = "insert into employee (name,age) values ('Frank',50)";
cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
//5. Query the records
sql = "select * from employee";
cmd = new SQLiteCommand(sql, conn);
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine("Name:" + reader["name"] + "\t Age:" + reader["age"]);
}
SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql,conn);
DataTable dt=new DataTable();
int count = adapter.Fill(dt);
for(int i=0;i<count;i++)
{
Console.WriteLine("Name: {0}\t Age: {1}", dt.Rows[i][0], dt.Rows[i][1]);
}
}
}
}