4

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.

9
  • you could save it as a stored procedure in your db and call it from code behind Commented May 23, 2014 at 7:15
  • No, because I am going to execute in many different databases. I prefer to execute it from the application Commented May 23, 2014 at 7:19
  • you could save your query in a text file and load it as string an execute in your db's Commented May 23, 2014 at 7:21
  • I have it in a text file, I have tried to translate this: stackoverflow.com/questions/650098/… to npgsql connector but no luck... Commented May 23, 2014 at 7:24
  • could you post the full code that you have tried? mask the ip's and other personal info, i just want to see the logic if possible please. also try executing a simple insert query just to rule out the possibility that your script fails Commented May 23, 2014 at 7:33

1 Answer 1

11

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Remove extra closing bracket at new NpgsqlConnection("yourconnectionstring")).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.