Last active
March 13, 2019 20:35
-
-
Save cjonstrup/009123b1ed2542b966d4ffacfbe78f13 to your computer and use it in GitHub Desktop.
C# Postgresql - Fast import
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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