问题
I get this error Microsoft.Data.Sqlite.SqliteException: 'SQLite Error 14: 'unable to open database file'.' when I try to run this code, it is a UWP application and I am using sqlite
private void btnContinue_Click(object sender, RoutedEventArgs e)
{
string datasource = @"F:\Curtis\Documents\Capstone\Capstone\Database\BobDB.db"; ;
using (SqliteConnection conn = new SqliteConnection(@"Data Source = " + datasource))
{
conn.Open();
SqliteCommand command = conn.CreateCommand();
command.CommandText = "Select TestTableTXT from TestTable;";
using (SqliteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
DatabaseTextBlock.Text = reader.GetString(0);
}
}
conn.Close();
}
}
回答1:
UWP apps are running in the sandbox and when you run them they are installed into it. They are not running in your source code bin folder of your project. In order to make your code up and running add your db file to your project Assets folder Assets\BobDB.db
.
Set Build Action of this file to Content
.
The good thing is that our file is now included to our Installed app folder. The bad thing is that it is read only. To overcome it we need to copy it to local app folder:
public MainPage()
{
this.InitializeComponent();
Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
string targetDbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database\\BobDB.db");
if (!File.Exists(targetDbPath))
{
var installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
using (var input = await installedLocation.OpenStreamForReadAsync("Assets\\BobDB.db"))
{
using (var output = await Windows.Storage.ApplicationData.Current.LocalFolder.OpenStreamForWriteAsync("Database\\BobDB.db", Windows.Storage.CreationCollisionOption.FailIfExists))
{
await input.CopyToAsync(output);
}
}
}
using (SqliteConnection conn = new SqliteConnection(@"Data Source = " + targetDbPath))
{
conn.Open();
...
来源:https://stackoverflow.com/questions/60807553/microsoft-data-sqlite-sqliteexception-sqlite-error-14-unable-to-open-databas