C# 创建 SQLite 数据库和表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15292880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create SQLite Database and table
提问by TinKerBell
Within C# application code, I would like to create and then interact with one or more SQLite databases.
在 C# 应用程序代码中,我想创建一个或多个 SQLite 数据库,然后与之交互。
How do I initialize a new SQLite database file and open it for reading and writing?
如何初始化一个新的 SQLite 数据库文件并打开它进行读写?
Following the database's creation, how do I execute a DDL statement to create a table?
创建数据库后,如何执行 DDL 语句来创建表?
采纳答案by Max
The next link will bring you to a great tutorial, that helped me a lot!
下一个链接将为您带来一个很棒的教程,对我帮助很大!
How to SQLITE in C#*domain is marked as inactive.
I nearly used everything in that article to create the SQLite database for my own C# Application.
我几乎使用了那篇文章中的所有内容来为我自己的 C# 应用程序创建 SQLite 数据库。
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGetand by adding the dll manually.
不要忘记下载 SQLite.dll,并将其添加为对您的项目的引用。这可以使用NuGet并通过手动添加 dll来完成。
After you added the reference, refer to the dll from your code using the following line on top of your class:
添加引用后,使用类顶部的以下行从代码中引用 dll:
using System.Data.SQLite;
using System.Data.SQLite;
You can find the dll's here:
您可以在此处找到 dll:
You can find the NuGet wayhere:
您可以在此处找到NuGet 方式:
Up next is the create script. Creating a database file:
接下来是创建脚本。创建数据库文件:
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();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
在 C# 中创建创建脚本后,我认为您可能想要添加回滚事务,它更安全并且可以防止您的数据库失败,因为数据将在最后作为原子操作提交到一大块数据库而不是小块,例如,它可能会在 10 次查询中的第 5 次失败。
Example on how to use transactions:
关于如何使用事务的示例:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}