Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute postgres script with npgsql

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.

like image 902
Za7pi Avatar asked Nov 02 '25 02:11

Za7pi


1 Answers

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();
like image 117
Za7pi Avatar answered Nov 03 '25 17:11

Za7pi