创建 SQLite 数据库和表 [英] Create SQLite Database and table

查看:43
本文介绍了创建 SQLite 数据库和表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Within C# application code, I would like to create and then interact with one or more SQLite databases.

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

How do I initialize a new SQLite database file and open it for reading and writing?

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

Following the database's creation, how do I execute a DDL statement to create a table?

推荐答案

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

The next link will bring you to a great tutorial, that helped me a lot!

如何在 C# 中使用 SQLITE

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

I nearly used everything in that article to create the SQLite database for my own C# Application.

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

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

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

After you added the reference, refer to the dll from your code using the following line on top of your class:

使用 System.Data.SQLite;

您可以在此处找到 dll:

You can find the dll's here:

SQLite DLL 的

您可以在此处找到 NuGet 方式:

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

在 C# 中创建创建脚本后,我认为您可能想要添加回滚事务,它更安全并且可以防止您的数据库失败,因为数据将在最后作为原子提交一大块对数据库的操作而不是小块操作,例如在 10 次查询中的第 5 次可能会失败.

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.

如何使用事务的示例:

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

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

这篇关于创建 SQLite 数据库和表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆