下一个链接将为您带来一个很棒的教程,这对我帮助很大!
如何在 C# 中使用 SQLITE:我几乎使用了那篇文章中的所有内容来为我自己的 C# 应用程序创建 SQLite 数据库。
前提条件
-
下载 SQLite.dll
- 通过添加SQLite DLL 的手动
- 或通过使用NuGet
-
将其添加为您的项目的参考
-
在类顶部使用以下行引用代码中的 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();
另请参阅此交易范围示例