Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query SQLite for whether a record exists?

In the commented-out line below, PlatypusId is red/not recognized, although it does exist in the corresponding table.

In the multi-line spanning assignment to queryResult, PlatypusId, where, and count are red/unrecognized.

    //var queryResult = await conn.Table<PlatypiRequested>().CountAsync().(x => x.PlatypusId.Equals(personId));
    var queryResult = from p in PlatypiRequested
                      where p.PlatypusId.Equals(platypusId)
                      select count;

IOW, when I add this:

    var conn = new SQLiteAsyncConnection(SQLitePath);
    var queryResult = await conn.Table<PlatypiRequested>().CountAsync().(x => x.

...nothing is proffered as a possibility following that "x => x."

What sort of code is necessary to query my SQLite table?

I am using the SQLite-net package/extension, but its documentation (what documentation?) is not overly verbose. Looking through both SQLite.cs and SQLiteAsync.cs, I'm none the wiser...

UPDATE

Okay, Mr. Harvey's answer comment led me to this working code (Count() was not available, just CountAsync()):

public async Task<bool> PlatypusAlreadyAdded(string platypusId)
{
    var conn = new SQLiteAsyncConnection(SQLitePath);
    var queryResult = await conn.Table<PlatypiRequested>().Where(x => x.PlatypusId == platypusId).CountAsync();
    return queryResult > 0;
}

As Jackie DeShannon (no relation to me, AFAIK) sang, "What the world needs now is a "SQLite/SQLite-net for C# Windows Store apps"" book (or at least a lengthy/informative blog post, containing examples of all the common types of SQL statements (CRUD)).

like image 496
B. Clay Shannon-B. Crow Raven Avatar asked Dec 03 '12 22:12

B. Clay Shannon-B. Crow Raven


People also ask

How do you check if a row already exists in SQLite?

Introduction to SQLite EXISTS operatorThe EXISTS operator is a logical operator that checks whether a subquery returns any row. In this syntax, the subquery is a SELECT statement that returns zero or more rows. If the subquery returns one or more row, the EXISTS operator return true.

Does exist in SQLite?

The SQLite EXISTS condition is used in combination with a subquery and is considered "to be met" if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

I think what you're really looking for is something like

var queryResult = await conn.Table<PeopleRequested>()
                            .Where(x => x.someField == someValue)
                            .CountAsync();  

Your way is not going to work, since the last . operator is expecting a method call, not an opening parenthesis or lambda expression.

like image 67
Robert Harvey Avatar answered Oct 07 '22 20:10

Robert Harvey