Frage

I'm working in .NET 4.0 with a Postgres database, thus using the Npgsql dll. I can't seem to find anywhere how to execute a sql file directly with a command.

It should be the same effect as it does when you launch psql.exe with -f parameter, but then in .NET code.

For example, now you have:

var cmd = new NpgsqlCommand(conn);
cmd.ExecuteNonQuery("insert into...");

And I need something like:

var cmd = new NpgsqlCommand(conn);
cmd.ExecuteFile("C:\... .sql");

I could read the entire file and execute it as a commandstring, but that doesn't have the same effect strangely enough.

Any help is highly appreciated.

War es hilfreich?

Lösung

Why not just write a simple extension method:

public static int ExecuteFile(this NpgsqlCommand cmd, string filename)
{
     string strText = System.IO.File.ReadAllText(filename, System.Text.Encoding.UTF8);
     cmd.CommandText = strText;
     return cmd.ExecuteNonQuery();
}

Or maybe you'd want to use a custom encoding, like System.Text.Encoding.Default, or something else, then use

public static int ExecuteFile(this NpgsqlCommand cmd, string filename, System.Text.Encoding enc)
{
     string strText = System.IO.File.ReadAllText(filename, enc);
     cmd.CommandText = strText;
     return cmd.ExecuteNonQuery();
}

if you declare it in a static class in namespace Npgsql, then you don't even need an additional include.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top