Execute postgres script with npgsql

Za7pi picture Za7pi · May 23, 2014 · Viewed 8.5k times · Source

I have a script (*.sql) which creates tables. I am using Visual studio 2010 with npgsql to access postgres database.

Could I execute a script from codebehind?

This is the code I have tried:

string sqlConnectionString = @"myconnection";

FileInfo file = new FileInfo(@"myfile.sql");

string script = file.OpenText().ReadToEnd();

NpgsqlConnection conn = new NpgsqlConnection(sqlConnectionString);

Server server = new Server(new ServerConnection(conn));

server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();

But But Visual studio dont recognize Server.

Answer

Za7pi picture Za7pi · May 23, 2014

I got it. Here the answer:

NpgsqlConnection _connPg = new NpgsqlConnection("yourconnectionstring"));

FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath("DatabaseSchema.sql"));
string script = file.OpenText().ReadToEnd();
var m_createdb_cmd = new NpgsqlCommand(script, _connPg);
_connPg.Open();
m_createdb_cmd.ExecuteNonQuery();
_connPg.Close();