创建SQLite数据库和表[关闭]

问题描述 投票:132回答:1

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

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

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

c# sqlite system.data.sqlite
1个回答
256
投票

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

How to SQLITE in C#

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

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

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

using System.Data.SQLite;

你可以在这里找到dll:

SQLite DLL's

你可以在这里找到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();

在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();
 }
© www.soinside.com 2019 - 2024. All rights reserved.