Skip to content

Instantly share code, notes, and snippets.

@oscarkuo
Created December 12, 2015 19:46
Show Gist options
  • Save oscarkuo/59cdd8034e44b799d458 to your computer and use it in GitHub Desktop.
Save oscarkuo/59cdd8034e44b799d458 to your computer and use it in GitHub Desktop.
Convert a SQLite table to a JSON file
using System;
using System.Data.SQLite;
using System.IO;
using System.Text;
using Newtonsoft.Json;
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 string MakeJson(string connectionString, string sql)
{
var builder = new StringBuilder();
var writer = new StringWriter(builder);
using (var jsonWriter = new JsonTextWriter(writer))
{
Execute(connectionString, sql, (SQLiteDataReader reader) =>
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("Results");
jsonWriter.WriteStartArray();
for (var i = 0; i < reader.FieldCount; ++i)
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName(reader.GetName(i));
jsonWriter.WriteValue(reader.GetValue(i));
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
});
jsonWriter.Flush();
return builder.ToString();
}
}
static void Main(string[] args)
{
var allDbConnectionString = @"Data Source=..\..\data\alldb.sqlite3;Version=3;";
var tempJsonFile = Path.GetTempFileName() + ".json";
File.WriteAllText(
tempJsonFile,
MakeJson(allDbConnectionString, "select * from Parts"));
Console.WriteLine("Done writing output to [" + tempJsonFile + "]");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment