I am trying to drop a database from aspnet(c#). But It is giving me an error: There are some connections. If I delete all the connections:
SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity
WHERE pg_stat_activity.pid <> pg_backend_pid() and pg_stat_activity.datname = 'databsename';
It gives me another error: connection is lose.
It is like if i execute the sentence above, It is closing all my connections.
I use npgsql as connector.
Here my code: The code inside a button:
NpgsqlConnection _connPgComienzo = new NpgsqlConnection("my_connection_to_other_DDBB_in_the_same_server;");
try
{
_connPgComienzo.Open();
FileInfo file1 = new FileInfo(Server.MapPath("desconectar.sql"));
string script_crear_bbdd = file1.OpenText().ReadToEnd();
var m_createdb_cmd1 = new NpgsqlCommand(script_crear_bbdd, _connPgComienzo);
m_createdb_cmd1.ExecuteNonQuery();
_connPgComienzo.Close();
_connPgComienzo.Open();
FileInfo file2 = new FileInfo(Server.MapPath("drop_bbdd.sql"));
string script_crear_bbdd2 = file2.OpenText().ReadToEnd();
var m_createdb_cmd2 = new NpgsqlCommand(script_crear_bbdd2, _connPgComienzo);
m_createdb_cmd2.ExecuteNonQuery();
_connPgComienzo.Close();
}
catch (Exception ex)
{
}
desconectar.slq:
SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity
WHERE pid <> pg_backend_pid() AND pg_stat_activity.datname = 'theDDBBIWantToDrop';
drop_bbdd.sql:
DROP DATABASE theDDBBIWantToDrop;
*Try to use
psql
to terminate yourpostgreSQL database
batch file(*.bat)
using c#, This .bat file must contain the following script to terminate your database connectionFor example
this code will create
pgTerminate.bat
file in this pathD:\Apps\RSTAR PGSQL DOTCONNECT\bin\Debug\PG
pgTerminate.bat
looks likecd /D D:\Apps
Note : before trying code you should manually create terminate bat file and test whether its working or not