Skip to content

Instantly share code, notes, and snippets.

@oscarkuo
Created December 12, 2015 07:26
Show Gist options
  • Save oscarkuo/47c780c7ca7557f74b41 to your computer and use it in GitHub Desktop.
Save oscarkuo/47c780c7ca7557f74b41 to your computer and use it in GitHub Desktop.
Read SQLite table columns
using System;
using System.Collections.Generic;
using System.Data.SQLite;
namespace Sqlite3ToJson
{
class Program
{
static void Execute(string connectionString, string sql, Action<SQLiteDataReader> action)
{
using (var connection = new SQLiteConnection(connectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = sql;
command.CommandType = System.Data.CommandType.Text;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
action(reader);
}
}
connection.Close();
}
}
static Dictionary<string, string> GetColumns(string connectionString, string table)
{
var query = "pragma table_info(" + table + ")";
var columns = new Dictionary<string, string>();
Execute(connectionString, query, (SQLiteDataReader reader) =>
{
columns[reader[1] as string] = reader[2] as string;
});
return columns;
}
static void Main(string[] args)
{
var allDbConnectionString = @"Data Source=..\..\data\alldb.sqlite3;Version=3;";
foreach (var c in GetColumns(allDbConnectionString, "Parts"))
{
Console.WriteLine(c.Key + " => " + c.Value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment