在C#应用程序代码中,我想创建一个或多个SQLite数据库并与之交互。
如何初始化一个新的SQLite数据库文件并打开它以进行读写操作?
在创建数据库后,如何执行DDL语句来创建表?
在C#应用程序代码中,我想创建一个或多个SQLite数据库并与之交互。
如何初始化一个新的SQLite数据库文件并打开它以进行读写操作?
在创建数据库后,如何执行DDL语句来创建表?
下一个链接将带您进入一篇非常好的教程,对我帮助很大!
如何在C#中使用SQLite:我几乎使用了那篇文章中的所有内容来为自己的C#应用程序创建SQLite数据库。
下载SQLite.dll
将其作为引用添加到您的项目中
在类的顶部使用以下行引用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();
另请参阅此transactionscope示例
System.Transactions.TransactionScope
的效果并不如预期,它会立即执行每个ExecuteNonQuery
,而不像SQLiteTransaction
那样一起执行。那么为什么要使用TransactionScope
呢? - MrCalvinSQLiteTransaction tr = m_dbConnection.BeginTransaction(); SQLiteCommand command = new SQLiteCommand(...); command.Transaction = tr;
而不是使用TransactionScope
。 - user643011