Is it possible to return dynamic objects or Dataset from a Sqlite Query?

前端 未结 5 1387
慢半拍i
慢半拍i 2020-12-06 08:39

I am using Sqlite.Net in my Xamarin.Forms application. So far it has been great at returning lists of objects if my object is a class like so:

Sq         


        
5条回答
  •  囚心锁ツ
    2020-12-06 09:14

    Unlike @Fabian Monkemoller, i was unable to get @User1's code to work straight away. This is a modified version that make use of nullable reference types and method-nesting to seperate the main-code from the try-catch block:

         public static object?[][]? ToDataSet(this SQLiteConnection sqlConnection, string query , bool includeColumnNamesAsFirstRow = true)
        {
            var stQuery = SQLite3.Prepare2(sqlConnection.Handle, query );
            var colLength = SQLite3.ColumnCount(stQuery);
            try
            {
                return SelectRows().ToArray();
            }
            catch (Exception e)
            {
                return null;
            }
            finally
            {
                if (stQuery != null)
                {
                    SQLite3.Finalize(stQuery);
                }
            }
    
            IEnumerable SelectRows()
            {
                if (includeColumnNamesAsFirstRow)
                {
                    yield return SelectColumnNames(stQuery, colLength).ToArray();
                }
    
                while (SQLite3.Step(stQuery) == SQLite3.Result.Row)
                {
                    yield return SelectColumns(stQuery, colLength).ToArray();
                }
    
                static IEnumerable SelectColumnNames(SQLitePCL.sqlite3_stmt stQuery, int colLength)
                {
                    for (int i = 0; i < colLength; i++)
                    {
                        yield return SQLite3.ColumnName(stQuery, i);
                    }
                }
    
                static IEnumerable SelectColumns(SQLitePCL.sqlite3_stmt stQuery, int colLength)
                {
                    for (int i = 0; i < colLength; i++)
                    {
                        var x = SQLitePCL.raw.sqlite3_column_decltype(stQuery, i);
                        yield return x switch
                        {
                            "text" => SQLite3.ColumnString(stQuery, i),
                            "integer" => SQLite3.ColumnInt(stQuery, i),
                            "bigint" => SQLite3.ColumnInt64(stQuery, i),
                            "real" => SQLite3.ColumnDouble(stQuery, i),
                            "blob" => SQLite3.ColumnBlob(stQuery, i),
                            "null" => null,
                            _ => throw new Exception($"Unexpected type encountered in for query {stQuery}")
                        };
                    }
                }
            }
        }
    
        

    提交回复
    热议问题