创建SQLite数据库和表

Tin*_*ell 143 c# sqlite system.data.sqlite

在C#应用程序代码中,我想创建一个或多个SQLite数据库然后进行交互.

初始化新的SQLite数据库文件并打开它进行读写的首选方法是什么?

在创建数据库之后,如何执行DDL语句来创建表?

Max*_*Max 275

下一个链接将为您带来一个很棒的教程,这对我帮助很大!

如何在C#中使用SQLITE

我几乎使用该文章中的所有内容为我自己的C#应用​​程序创建SQLite数据库.

不要忘记下载SQLite.dll,并将其添加为项目的参考.这可以使用NuGet并手动添加dll 来完成.

添加引用后,请使用代码顶部的以下行从代码中引用dll:

using System.Data.SQLite;

你可以在这里找到dll:

SQLite DLL

你可以在这里找到NuGet方式:

的NuGet

接下来是创建脚本.创建数据库文件:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();
Run Code Online (Sandbox Code Playgroud)

在C#中创建创建脚本之后,我认为您可能希望添加回滚事务,它更安全,它会使您的数据库失败,因为数据最终会在一个大块中作为原子操作提交给数据库而不是小块,例如,它可能在10个查询中的第5个失败.

有关如何使用事务的示例:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }
Run Code Online (Sandbox Code Playgroud)

  • 很清楚的答案.+1.这是另一个示例,它向您展示了SQLite在插入和检索记录时的速度:http://www.technical-recipes.com/2016/using-sqlite-in-c-net-environments/ (5认同)
  • 我更喜欢`SQLiteTransaction tr = m_dbConnection.BeginTransaction(); SQLiteCommand 命令 = new SQLiteCommand(...); command.Transaction = tr;` 优于使用 `TransactionScope` (2认同)