【问题标题】:Create SQLite Database and table创建 SQLite 数据库和表
【发布时间】:2013-02-23 22:21:36
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# sqlite system.data.sqlite


    【解决方案1】:

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

    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();
     }
    

    【讨论】:

    • 很好的明确答案。 +1 了。这是另一个示例,向您展示 SQLite 在插入和检索记录方面的速度:technical-recipes.com/2016/using-sqlite-in-c-net-environments
    • 在我的测试中使用System.Transactions.TransactionScope 没有按预期工作,它会立即执行每个ExecuteNonQuery,而不是一起执行,就像SQLiteTransaction。为什么使用TransactionScope
    • 我更喜欢 SQLiteTransaction tr = m_dbConnection.BeginTransaction(); SQLiteCommand command = new SQLiteCommand(...); command.Transaction = tr; 而不是 TransactionScope
    • Sql事务仅用于数据语句。 DDL 绝不是事务的一部分
    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    相关资源
    最近更新 更多