Ejemplo n.º 1
0
        private static void ShowSqlConsole(SQLiteDatabase database)
        {
            Console.WriteLine("Direct SQL interface to SQLite. Enter query. Leave with 'exit' command.");
            var instructionList = new InstructionList();

            foreach (var query in instructionList.ParseStream(Console.In))
            {
                if (query == "exit")
                {
                    return;
                }
                // Note: we need the direct connection to DB, not a transaction.
                // This is because some instructions can't be done inside transaction scope (like vacuum, reindex)
                using (var connection = database.CreateOpenAndInitializeConnection())
                {
                    using (var cmd = connection.CreateCommand())
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = query;

                        try
                        {
                            using (var reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    for (int c = 0; c < reader.FieldCount; c++)
                                    {
                                        Console.Write(reader.GetName(c).PadRight(10) + "|");
                                    }
                                    Console.WriteLine();
                                }
                                while (reader.Read())
                                {
                                    for (int c = 0; c < reader.FieldCount; c++)
                                    {
                                        object value     = reader.GetValue(c);
                                        string formatted = string.Format("{0}", value).PadRight(10).Substring(0, 10);
                                        Console.Write(formatted + "|");
                                    }
                                    Console.WriteLine();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error: {0}", ex);
                        }
                    }
                }
            }
        }