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

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

问题描述

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

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

什么是preferred方法来初始化一个新的SQLite数据库文件并打开它进行阅读和写作?

What is the preferred method to initialize a new SQLite database file and open it for reading and writing?

随着数据库的创建,请问有什么可以执行DDL语句来创建一个表?

Following the database's creation, how may 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.

在您添加参考,使用你的类的顶部以下行从code指的是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");

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

string sql = "insert into highscores (name, score) values ('Me', 9001)";

SQLiteCommand 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 to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

有关如何使用交易实例:

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

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

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