Skip to content

Instantly share code, notes, and snippets.

@cjonstrup
Last active March 13, 2019 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjonstrup/009123b1ed2542b966d4ffacfbe78f13 to your computer and use it in GitHub Desktop.
Save cjonstrup/009123b1ed2542b966d4ffacfbe78f13 to your computer and use it in GitHub Desktop.
C# Postgresql - Fast import
using (var connection = HeroukoPostgresql)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
connection.Open();
var trans = connection.BeginTransaction();
try
{
ExecuteNonQuery("TRUNCATE xxx", connection);
const string query = "COPY xxx (a,b,c,d) FROM STDIN (FORMAT BINARY)";
using (var writer = connection.BeginBinaryImport(query))
{
foreach (var price in prices)
{
writer.StartRow();
writer.Write(a, NpgsqlDbType.Integer);
writer.Write(b, NpgsqlDbType.Date);
writer.Write(c, NpgsqlDbType.Varchar);
writer.Write(d, NpgsqlDbType.Numeric);
}
}
trans.Commit();
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine("Error importing xxx : " + ex.Message);
}
finally
{
try { connection.Close(); }
catch
{
// ignored
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment