【发布时间】:2014-05-25 12:13:24
【问题描述】:
我想从给定的流 (FileStream/Memorystream) 访问 SQLite 数据库?
这是我目前的代码(它将文件读入内存流,然后在 SQLite 中打开):
if (File.Exists(path_DB))
{
byte[] file = File.ReadAllBytes(path_DB);
MemoryStream mem = new MemoryStream(file);
using (SQLiteConnection destination = new SQLiteConnection("Data Source=" + mem + ";Version=3;"))
{
destination.Open();
using (SQLiteCommand command = new SQLiteCommand())
{
command.Connection = destination;
command.CommandText = "SELECT Name FROM MyTable;";
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader["Name"].ToString());
}
}
}
}
}
这段代码触发了我
SQL 逻辑错误或缺少数据库,没有这样的表:MyTable
command.ExecuteReader()。 path_DB 引用的文件确实有该表。
我哪里出错了?
//编辑:已更改
byte[] file = File.ReadAllBytes(path_DB);
MemoryStream mem = new MemoryStream();
到
byte[] file = File.ReadAllBytes(path_DB);
MemoryStream mem = new MemoryStream(file);
此外,我可以将现有数据库加载到内存中,然后将内存数据库再次保存到磁盘,如下所示:
if (File.Exists(path_DB))
{
using (SQLiteConnection destination = new SQLiteConnection("Data Source=:memory:;Version=3;"))
{
SQLiteConnection source = new SQLiteConnection("Data Source=" + path_DB + ";Version=3;"); //;Password=" + textBox2.Text + "
source.Open();
destination.Open();
source.BackupDatabase(destination, "main", "main", -1, null, 0);
source.Close();
using (SQLiteCommand command = new SQLiteCommand())
{
command.Connection = destination;
command.CommandText = "SELECT Name FROM MyTable;";
using (System.Data.SQLite.SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader["Name"].ToString());
}
}
}
source = new SQLiteConnection("Data Source=" + path_DB + ";Version=3;"); //;Password=" + textBox2.Text + "
source.Open();
// save memory db to file
destination.BackupDatabase(source, "main", "main", -1, null, 0);
source.Close();
}
}
所以我想,一定还有一种方法可以通过直接(解密)流来做到这一点!?
【问题讨论】: