创建SQLite数据库和表格

176

在C#应用程序代码中,我想创建一个或多个SQLite数据库并与之交互。

如何初始化一个新的SQLite数据库文件并打开它以进行读写操作?

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

1个回答

338

下一个链接将带您进入一篇非常好的教程,对我帮助很大!

如何在C#中使用SQLite:我几乎使用了那篇文章中的所有内容来为自己的C#应用程序创建SQLite数据库。

前置条件

  1. 下载SQLite.dll

  2. 将其作为引用添加到您的项目中

  3. 在类的顶部使用以下行引用dll:using System.Data.SQLite;

代码示例

以下代码创建一个数据库文件,并将记录插入其中:

// this creates a zero-byte file
SQLiteConnection.CreateFile("MyDatabase.sqlite");

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

// varchar will likely be handled internally as TEXT
// the (20) will be ignored
// see https://www.sqlite.org/datatype3.html#affinity_name_examples
string sql = "Create Table highscores (name varchar(20), score int)";
// you could also write sql = "CREATE TABLE IF NOT EXISTS highscores ..."
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#创建创建脚本后,您可能希望添加回滚事务。这将确保数据最终作为原子操作一次性提交到数据库中,而不是以小块形式提交,例如在第5个或第10个查询时失败。

如何使用事务的示例:

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

   // Indicates that creating the SQLiteDatabase went succesfully,
   // so the database can be committed.
   transaction.Complete();
}

第三方编辑

要读取记录,您可以使用ExecuteReader()


sql = "SELECT score, name, Length(name) as Name_Length 
       FROM highscores WHERE score > 799";
command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();

while(reader.Read())
{
   Console.WriteLine(reader[0].ToString()  + " " 
                  +  reader[1].ToString()  + " " 
                  +  reader[2].ToString());            
}
dbConnection.Close();

另请参阅此transactionscope示例


6
很好的明确回答。+1。以下是另一个示例,展示了SQLite在插入和检索记录方面有多快:http://www.technical-recipes.com/2016/using-sqlite-in-c-net-environments/ - AndyUK
在我的测试中,使用 System.Transactions.TransactionScope 的效果并不如预期,它会立即执行每个 ExecuteNonQuery ,而不像 SQLiteTransaction 那样一起执行。那么为什么要使用 TransactionScope 呢? - MrCalvin
2
我更喜欢使用 SQLiteTransaction tr = m_dbConnection.BeginTransaction(); SQLiteCommand command = new SQLiteCommand(...); command.Transaction = tr; 而不是使用 TransactionScope - user643011
SQL事务仅适用于数据语句。DDL永远不是事务的一部分。 - Boppity Bop
使用TransactionScope(),Max的答案可能是错误的吗? - James Kerfoot
非常好的回答,详细而精彩。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接