欢迎投稿

今日深度:

C# 使用SQLite,它是一个零配置的数据

C# 使用SQLite,它是一个零配置的数据


SQLite是一个进程内的轻量级嵌入式数据库,它的数据库就是一个文件,实现了自给自足、无服务器、零配置的、事务性的SQL数据库引擎。它是一个零配置的数据库,这就体现出来SQLite与其他数据库的最大的区别:SQLite不需要在系统中配置,直接可以使用。且SQLite不是一个独立的进程,可以按应用程序需求进行静态或动态连接。SQLite可直接访问其存储文件。

1. 安装:System.Data.SQLite 组件

2. 创建数据表

首先需要在数据创建一张表,才能添加数据,有数据了才能演示查询,修改和删除。

创建一张Person表。

string dbfile = @"URI=file:sql.db";
SQLiteConnection cnn = new SQLiteConnection(dbfile);
cnn.Open();

string sql = "Create table Person (Id integer primary key, Name text);";
SQLiteCommand cmd = new SQLiteCommand(sql, cnn);
cmd.ExecuteNonQuery();
cnn.Close();

 3.添加行数据

string dbfile = @"URI=file:sql.db";
SQLiteConnection cnn = new SQLiteConnection(dbfile);
cnn.Open();

string sql = "insert into  Person (Id , Name) values(1,'Mike');";
SQLiteCommand cmd = new SQLiteCommand(sql, cnn);
cmd.ExecuteNonQuery();
cnn.Close();

Console.WriteLine("Insert row OK");

4. 查询数据

string dbfile = @"URI=file:sql.db";

SQLiteConnection cnn = new SQLiteConnection(dbfile);

cnn.Open();

string sql = "Select * From  Person";

SQLiteCommand cmd = new SQLiteCommand(sql, cnn);

SQLiteDataReader reader = cmd.ExecuteReader();

while(reader.Read())

{

  Console.WriteLine($"{reader.GetInt32(0)}  {reader.GetString(1)} ");

}

reader.Close();

cnn.Close();

5. 更新数据

string dbfile = @"URI=file:sql.db";
SQLiteConnection cnn = new SQLiteConnection(dbfile);
cnn.Open();

string sql = "update  Person set Name='Jim jones' where id=1;";
SQLiteCommand cmd = new SQLiteCommand(sql, cnn);
cmd.ExecuteNonQuery();
cnn.Close();

Console.WriteLine("Update row OK");

6.删除数据

string dbfile = @"URI=file:sql.db";
SQLiteConnection cnn = new SQLiteConnection(dbfile);
cnn.Open();

string sql = "delete from  Person where id=3;";
SQLiteCommand cmd = new SQLiteCommand(sql, cnn);
cmd.ExecuteNonQuery();
cnn.Close();
Console.WriteLine("Delete row OK");

实现了基本的数据操作,增删改查。在日常应用中稍加修改就即可使用。

www.htsjk.Com true http://www.htsjk.com/SQLite/45623.html NewsArticle C# 使用SQLite,它是一个零配置的数据 SQLite是一个进程内的轻量级嵌入式数据库它的数据库就是一个文件实现了自给自足、无服务器、零配置的、事务性的SQL数据库引擎。它是一个零配置...
评论暂时关闭