How to perform raw SQLite query (With multiple row result) through SQLiteAsyncConnection

时光怂恿深爱的人放手 提交于 2019-12-24 07:58:15

问题


I do not have a class map to a table. I'm referring to the following thread. The get the number of row in a table, I am applying the following technique

How to perform raw SQLite query through SQLiteAsyncConnection

SQLiteAsyncConnection conn = new SQLiteAsyncConnection(DATABASE_NAME);
int profileCount = await conn.ExecuteScalarAsync<int>("select count(*) from " + PROFILE_TABLE);

Now, instead of obtaining result as number of row, I would like to retrieve result in multiple row data.

In Java, to obtain multiple row result data, I would perform

Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    // For every cursor, obtain its col data by 
    // cursor.getLong(0), cursor.getInt(1), ...
    cursor.moveToNext();
}

Given a same sql statement, how can I achieve using SQLiteAsyncConnection?


回答1:


I added 2 new functions into SQLite.cs. Not elegant, but it works for me.

    // Invented by yccheok :)
    public IEnumerable<IEnumerable<object>> ExecuteScalarEx()
    {
        if (_conn.Trace)
        {
            Debug.WriteLine("Executing Query: " + this);
        }

        List<List<object>> result = new List<List<object>>();
        var stmt = Prepare();

        while (SQLite3.Step(stmt) == SQLite3.Result.Row)
        {
            int columnCount = SQLite3.ColumnCount(stmt);

            List<object> row = new List<object>();
            for (int i = 0; i < columnCount; i++)
            {
                var colType = SQLite3.ColumnType(stmt, i);
                object val = ReadColEx (stmt, i, colType);
                row.Add(val);
            }
            result.Add(row);
        }
        return result;
    }

    // Invented by yccheok :)
    object ReadColEx (Sqlite3Statement stmt, int index, SQLite3.ColType type)
    {
        if (type == SQLite3.ColType.Null) {
            return null;
        } else {
            if (type == SQLite3.ColType.Text) {
                return SQLite3.ColumnString (stmt, index);
            }
            else if (type == SQLite3.ColType.Integer)
            {
                return (int)SQLite3.ColumnInt (stmt, index);
            }
            else if (type == SQLite3.ColType.Float)
            {
                return SQLite3.ColumnDouble(stmt, index);
            }
            else if (type == SQLite3.ColType.Blob)
            {
                return SQLite3.ColumnBlob(stmt, index);
            }
            else
            {
                throw new NotSupportedException("Don't know how to read " + type);
            }
        }
    }


来源:https://stackoverflow.com/questions/13679537/how-to-perform-raw-sqlite-query-with-multiple-row-result-through-sqliteasyncco

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!