Search code examples
c#databasesqlitesqlite-netsqlite-net-extensions

How to make low level/plain SQL queries with SQLite-Net Extensions?


I'm using SQLite-Net Extensions and I want to check if a table exists, before I do some operations on it. This is what I tried:

await this.database.ExecuteScalarAsync<int>("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{0}'", tableName).ContinueWith( t =>
{
    System.Diagnostics.Debug.WriteLine(t.Result);
});

The output is 0. If I query this directly on the database I get a result (1). Then I tried

var tableQuery = string.Format("SELECT name FROM sqlite_master WHERE type='table' AND name='{0}'", tableName);
var result = await this.database.ExecuteAsync(tableQuery);

and I get an exception:

SQLite.SQLiteException: Row
  at SQLite.SQLiteCommand.ExecuteNonQuery () [0x0009b] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLite.cs:2172 
  at SQLite.SQLiteConnection.Execute (System.String query, System.Object[] args) [0x00040] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLite.cs:659 
  at SQLite.SQLiteAsyncConnection+<ExecuteAsync>c__AnonStorey9.<>m__0 () [0x00013] in /Users/fak/Dropbox/Projects/sqlite-net/src/SQLiteAsync.cs:222 
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <d18287e1d683419a8ec3216fd78947b9>:0 
  at System.Threading.Tasks.Task.Execute () [0x00010] in <d18287e1d683419a8ec3216fd78947b9>:0 
  at App.Database+<ClearTable>d__63.MoveNext () [0x00069] in xxx\Database.cs:1011 
  at App.Util.Helper+<CleanUpTemporaryFiles>d__8.MoveNext () [0x0013a] in xxx\Helper.cs:200 
  at App.Pages.DetailPage+<OnDisappearing>d__23.MoveNext () [0x000b1] in xxx\DetailPage.xaml.cs:449 

For QueryAsync you need an object with a parameterless constructor.

Now I don't know how to make a simple SELECT query. Is there also a way to get a more detailed exception message than Row?


Solution

  • The way you are passing parameters into your SQL is incorrect. As per the docs, instead of

    AND name='{0}'
    

    you should use:

    name = ?