Содержание
- How to Solve Error Message ERROR: database “database_name” is being accessed by other users when dropping PostgreSQL database in Microsoft Windows
- Introduction
- How to Solve Error Message ERROR: database “database_name” is being accessed by other users
- Postgresql-невозможно удалить базу данных из-за некоторых автоматических подключений к БД
- 9 ответов:
- TutorialDBA — Support | Training | Consultant
- PostgreSQL Drop Database
- Comments
- Post a Comment
- Popular posts from this blog
- Ora2PG — Oracle/MySQL to Postgres DB migration Version 20.0
- spfile and pfile errors
- How to find the server is whether standby (slave) or primary(master) in Postgresql replication ?
- How to Return a Result Set from a PostgreSQL Stored Procedure
- 7 Steps to configure BDR replication in postgresql
- dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users
- Responses
- Browse pgsql-admin by date
- Re: dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users
- In response to
- Browse pgsql-admin by date
How to Solve Error Message ERROR: database “database_name” is being accessed by other users when dropping PostgreSQL database in Microsoft Windows
Introduction
An error appear upon executing a certain query in the PostgreSQL database server is exist as part of the discussion in this article. Actually, the query is for dropping a database exist in a PostgreSQL database server. In this case, the process for dropping or removing the PostgreSQL database is in a local device running using Microsoft Windows. Before going further to the solution, the following is the actual execution of the query which is triggering the error message :
So, the process for executing the query ends in failure as in the above output command. The reason is actually exist as part of the error message. So, the process for dropping or removing the PostgreSQL database end in failure because it is currently accessed by several users. In the above output, it is being accessed by 3 users. That is why because it currently utilized by several users, the drop or the removal process ends in failure.
How to Solve Error Message ERROR: database “database_name” is being accessed by other users
So, this part is actually focusing onto the solution. In other words, just find a way to drop or to remove the database although it is currently still in used. Morevoer, there are several user currently using it. In other words, there are several connections from several user to the database. So, the process for removing or dropping PostgreSQL database server is not possible. Actually, there is some sort of mechanism for doing that. Just execute the drop database query with an additional parameter. This additional parameter is for forcing to drop or to remove PostgreSQL database server despite of several user connectivity. Just perform the following query as follows :
As it exist in the above query command execution, there is an additional parameter to be able to do it. That additional parameter is ‘with(force)’. And finally, it ends in a success.
Источник
Postgresql-невозможно удалить базу данных из-за некоторых автоматических подключений к БД
всякий раз, когда я пытаюсь удалить базу данных, я получаю:
когда я использую:
Я прекратил соединение с этой БД, но если я попытаюсь удалить базу данных после этого, кто-то автоматически подключится к этой базе данных и даст эту ошибку. Что может быть, что делать?
Никто не использует эту базу данных, кроме меня.
9 ответов:
вы можете предотвратить будущие соединения:
(и, возможно, другие пользователи и роли; см. l+ на psql )
затем вы можете завершить все подключения к этой БД, кроме собственного:
на старых версиях pid называлась procpid так что вам придется смириться с этим.
так как вы отозвали CONNECT права, все, что пытается автоматически подключиться, больше не должно быть в состоянии сделать это.
теперь вы сможете отбросить ДЕЦИБЕЛ.
это не будет работать, если вы используете суперпользовательские соединения для обычных операций, но если вы делаете это, вам нужно сначала решить эту проблему.
всякий раз, когда я пытаюсь удалить базу данных, я получаю:
сначала вам нужно отменить
это наверняка сработает.
просто проверьте, что такое соединение, откуда оно исходит. Вы можете увидеть все это в:
возможно, это ваша связь?
Я нашел решение этой проблемы попробуйте запустить эту команду в терминале
убить процесс по этой команде
если нет потенциального влияния на другие службы на вашем компьютере, просто service postgresql restart
Это означает, что другой пользователь обращается к базе данных. Просто перезапустите postgresql. Эта команда будет делать трюк
затем попробуйте удалить базу данных:
это будет делать трюк. Счастливого кодирования
pgAdmin 4 решение с помощью UI
сначала включите показать активность на приборной панели, если у вас нет:
теперь отключите все процессы, использующие БД:
- щелкните имя БД
- Щелкните Панель Мониторинга > Сеансы
- Нажмите кнопку «Обновить» значок
- щелкните значок Удалить (x) рядом с каждым процессом, чтобы завершить их
теперь должна быть возможность удалить БД.
в моем случае я использую AWS Redshift (на основе Postgres). И, кажется, нет никаких других подключений к БД, но я получаю эту же ошибку.
в моем случае кажется, что кластер баз данных все еще выполняет некоторую обработку в базе данных, и хотя нет других внешних/пользовательских подключений, база данных все еще используется внутри. Я нашел это, выполнив следующее:
так что мой Хак должен был написать цикл в моем коде, ища строки с моим именем базы данных в нем. (конечно, цикл не бесконечен, а является сонным циклом и т. д.)
если строки найдены, перейдите к удалению каждого PID, один за другим.
если строки не найдены, перейдите к удалению базы данных
Примечание: В моем случае я пишу тесты Java unit/system, где это можно считать приемлемым. Это неприемлемо для производственного кода.
вот полный Хак, в Java (игнорировать мои тестовые / служебные классы).
в терминале попробуйте эту команду:
501 1445 3645 0 12: 05AM 0: 00.03 postgres: sasha dbname [местный] холостом ходу
третий номер (3645) — PID.
вы можете удалить этот
и после этого запустите соединение PostgreSQL.
Источник
TutorialDBA — Support | Training | Consultant
PostgreSQL Drop Database
- Get link
- Other Apps
- dropdb — remove a PostgreSQL database
- dropdb destroys an existing PostgreSQL database. The user who executes this command must be a database superuser or the owner of the database.
- dropdb is a wrapper around the SQL command DROP DATABASE. There is no effective difference between dropping databases via this utility and via other methods for accessing the server.
- Above statement throws error becouse database «sales» is being accessed by other users We cannot drop a database that has any open connections/session, including our own connection from psql or pgAdmin III. We must switch to another database or template1 if we want to delete the database we are currently connected to. Thus, it might be more convenient to use the program dropdb instead which is a wrapper around this command.
- another way is we can kill the session using following command
- DROP DATABASE — remove a database
- DROP DATABASE drops a database. It removes the catalog entries for the database and deletes the directory containing the data. It can only be executed by the database owner. Also, it cannot be executed while you or anyone else are connected to the target database. (Connect to postgres or any other database to issue this command.)
- DROP DATABASE cannot be undone. Use it with care
- DROP DATABASE cannot be executed inside a transaction block.
- This command cannot be executed while connected to the target database. Thus, it might be more convenient to use the program dropdb instead, which is a wrapper around this command.
- Get link
- Other Apps
Popular posts from this blog
Ora2PG — Oracle/MySQL to Postgres DB migration Version 20.0
spfile and pfile errors
How to find the server is whether standby (slave) or primary(master) in Postgresql replication ?
]$ pg_controldata /usr/local/pgsql/data84/ Database cluster state: in archive recovery —> This is Standby Database Database cluster state: in production —> This is Production Database [Master] Method 2 You can use pg_is_in_recovery() which returns True if recovery is still in progress(so the server is running in standby mode or slave) postgres=# select pg_is_in_recovery(); pg_is_in_recovery ——————- t (1 row) If Return false so the server is running in primary mode or master postgres=# select pg_is_in_recovery(); pg_is_in_recovery ——————- f (1 row)
How to Return a Result Set from a PostgreSQL Stored Procedure
7 Steps to configure BDR replication in postgresql
/bdr-bdr-pg-REL9_4_12-1 $ ./configure —prefix=/usr/lib/postgresql/9.4 —enable-debug —with-openssl $ make -j4 -s install-world $ cd
/bdr-bdr-plugin-1.0.2 $ PATH=/usr/lib/postgresql/9.4/bin:»$PATH» ./c
Источник
dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users
| From: | Gourish Singbal |
|---|---|
| To: | pgsql-admin(at)postgresql(dot)org |
| Subject: | dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users |
| Date: | 2005-02-21 14:21:10 |
| Message-ID: | 674d1f8a0502210621233cf44e@mail.gmail.com |
| Views: | Raw Message | Whole Thread | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-admin |
This Error message was given when i was dropping the database.
There are idle connections to the database as seen from ps -ef | grep postgres
How can i drop the database with out restarting the postgres server.
FYI: i am dropping the database to perform restoration of this backup
database using psql from production.
Responses
- Re: dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users at 2005-02-23 05:41:41 from Gourish Singbal
Browse pgsql-admin by date
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Gourish Singbal | 2005-02-21 15:49:06 | Re: ERROR: 40P01: |
| Previous Message | Lorenza Ferrario | 2005-02-21 13:47:48 | pg_passwd file missing |
Copyright © 1996-2023 The PostgreSQL Global Development Group
Источник
Re: dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users
| From: | Gourish Singbal |
|---|---|
| To: | «Thomas F(dot) O’Connell» |
| Cc: | PgSQL Admin |
Subject: Re: dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users Date: 2005-02-28 05:42:15 Message-ID: 674d1f8a05022721424824ac01@mail.gmail.com Views: Raw Message | Whole Thread | Download mbox | Resend email Thread: Lists: pgsql-admin
Thanks a million,
pkill -f ‘postgres: postgres ‘
On Fri, 25 Feb 2005 10:30:31 -0600, Thomas F. O’Connell
wrote:
> pkill -f ‘postgres: postgres ‘
>
> Much cleaner than the previous recipe for those with pkill.
>
> -tfo
>
> —
> Thomas F. O’Connell
> Co-Founder, Information Architect
> Sitening, LLC
> http://www.sitening.com/
> 110 30th Avenue North, Suite 6
> Nashville, TN 37203-6320
> 615-260-0005
>
> —————————(end of broadcast)—————————
> TIP 8: explain analyze is your friend
>
In response to
- Re: dropdb: database removal failed: ERROR: database «database_name» is being accessed by other users at 2005-02-25 16:30:31 from Thomas F.O’Connell
Browse pgsql-admin by date
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Maritza Landsberg | 2005-02-28 07:13:30 | Error |
| Previous Message | knaicker | 2005-02-28 05:41:39 | unsubscribe |
Copyright © 1996-2023 The PostgreSQL Global Development Group
Источник
I create an NpgsqlConnection and do some stuff in a database, then try to drop that database. This fails with
Npgsql.PostgresException : 55006: database "test_settings_637363918866651378" is being accessed by other users
Data:
Severity: ERROR
InvariantSeverity: ERROR
SqlState: 55006
MessageText: database "test_settings_637363918866651378" is being accessed by other users
Detail: Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information.
File: dbcommands.c
Line: 888
Routine: dropdb
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
at Npgsql.NpgsqlDataReader.NextResult()
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteNonQuery()
This happens even if I call NpgsqlConnection.ChangeDatabase() to change to another database and even if I call NpgsqlConnection.Dispose() and open a new connection (to the «postgres» database) and try to drop my database through that.
It seems like Npgsql is still holding the connection open, probably due to connection pooling. How do I actually disconnect from the database, so it can be dropped?
Introduction
An error appear upon executing a certain query in the PostgreSQL database server is exist as part of the discussion in this article. Actually, the query is for dropping a database exist in a PostgreSQL database server. In this case, the process for dropping or removing the PostgreSQL database is in a local device running using Microsoft Windows. Before going further to the solution, the following is the actual execution of the query which is triggering the error message :
C:>psql -Upostgres
Password for user postgres:
psql (14.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=# drop database mydb;
ERROR: database "mydb" is being accessed by other users
DETAIL: There are 3 other sessions using the database.
So, the process for executing the query ends in failure as in the above output command. The reason is actually exist as part of the error message. So, the process for dropping or removing the PostgreSQL database end in failure because it is currently accessed by several users. In the above output, it is being accessed by 3 users. That is why because it currently utilized by several users, the drop or the removal process ends in failure.
So, this part is actually focusing onto the solution. In other words, just find a way to drop or to remove the database although it is currently still in used. Morevoer, there are several user currently using it. In other words, there are several connections from several user to the database. So, the process for removing or dropping PostgreSQL database server is not possible. Actually, there is some sort of mechanism for doing that. Just execute the drop database query with an additional parameter. This additional parameter is for forcing to drop or to remove PostgreSQL database server despite of several user connectivity. Just perform the following query as follows :
C:>psql -Upostgres
Password for user postgres:
psql (14.2)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=# drop database mydb with(force);
DROP DATABASES
As it exist in the above query command execution, there is an additional parameter to be able to do it. That additional parameter is ‘with(force)’. And finally, it ends in a success.
в моем случае я использую AWS Redshift (на основе Postgres).
И, кажется, нет никаких других подключений к БД, но я получаю эту же ошибку.ERROR: database "XYZ" is being accessed by other usersв моем случае кажется, что кластер баз данных все еще выполняет некоторую обработку в базе данных, и хотя нет других внешних/пользовательских подключений, база данных все еще используется внутри. Я нашел это, выполнив следующее:
SELECT * FROM stv_sessions;так что мой Хак должен был написать цикл в моем коде, ища строки с моим именем базы данных в нем. (конечно, цикл не бесконечен, а является сонным циклом и т. д.)
SELECT * FROM stv_sessions where db_name = 'XYZ';если строки найдены, перейдите к удалению каждого PID, один за другим.
SELECT pg_terminate_backend(PUT_PID_HERE);если строки не найдены, перейдите к удалению базы данных
DROP DATABASE XYZ;Примечание: В моем случае я пишу тесты Java unit/system, где это можно считать приемлемым. Это неприемлемо для производственного кода.
вот полный Хак, в Java (игнорировать мои тестовые / служебные классы).
int i = 0; while (i < 10) { try { i++; logStandardOut("First try to delete session PIDs, before dropping the DB"); String getSessionPIDs = String.format("SELECT stv_sessions.process, stv_sessions.* FROM stv_sessions where db_name = '%s'", dbNameToReset); ResultSet resultSet = databaseConnection.execQuery(getSessionPIDs); while (resultSet.next()) { int sessionPID = resultSet.getInt(1); logStandardOut("killPID: %s", sessionPID); String killSessionPID = String.format("select pg_terminate_backend(%s)", sessionPID); try { databaseConnection.execQuery(killSessionPID); } catch (DatabaseException dbEx) { //This is most commonly when a session PID is transient, where it ended between my query and kill lines logStandardOut("Ignore it, you did your best: %s, %s", dbEx.getMessage(), dbEx.getCause()); } } //Drop the DB now String dropDbSQL = String.format("DROP DATABASE %s", dbNameToReset); logStandardOut(dropDbSQL); databaseConnection.execStatement(dropDbSQL); break; } catch (MissingDatabaseException ex) { //ignore, if the DB was not there (to be dropped) logStandardOut(ex.getMessage()); break; } catch (Exception ex) { logStandardOut("Something went wrong, sleeping for a bit: %s, %s", ex.getMessage(), ex.getCause()); sleepMilliSec(1000); } }
|
postgres=# DROP DATABASE target_db; ERROR: database «target_db» is being accessed by other users DETAIL: There is 1 other session using the database. postgres=# |
для начала киляем конекты:
PostgreSQL 9.2 и выше:
|
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = ‘target_db’ AND pid <> pg_backend_pid(); |
PostgreSQL 9.1 и ниже:
|
SELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_activity WHERE pg_stat_activity.datname = ‘target_db’ AND procpid <> pg_backend_pid(); |
далее можно удалять
DROP DATABASE target_db
==================================================================================================
ну или так:
При удалении базы появляется ошибка о активных пользователях
drop database «SMS_Broadcaster»;
ERROR: database «SMS_Broadcaster» is being accessed by other users
DETAIL: There are 8 other sessions using the database.
Для начала запретим новые соединения с базой командой где «SMS_Broadcaster» – имя базы, postgres – владелец базы
REVOKE CONNECT ON DATABASE «SMS_Broadcaster» FROM PUBLIC, postgres;
Далее разрываем все активные соединения
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
— don’t kill my own connection!
pid <> pg_backend_pid()
— don’t kill the connections to other databases
AND datname = ‘ SMS_Broadcaster ‘ ;
После применения данной команды, будет показано сколько пользователей было отключено
Теперь можно дропать базу
drop database «SMS_Broadcaster»;
Для восстановления доступа к базе, если снова будет создана база данных, выполним следующую команду
GRANT CONNECT ON DATABASE «SMS_Broadcaster» TO postgres;
https://github.com/midnight47/
when I try from base management it says:
Could not drop database !
and when I try to drop via terminal:
dropdb: database removal failed: ERROR: database «database» is being accessed by other users
DETAIL: There are 4 other session(s) using the database.
I can drop other databases, but not the one I need to drop
any other possibilities?
2Ответы
Best Answer
Restarting the server may not fix this. If a user is logged into PostgreSQL, then restarting Odoo won’t disconnect them. A better answer would be to restart PostgreSQL and try again.
Best Answer
Restart the service ( /etc/init.d/openerp-server restart) and immediately try again. If you are going to drop the database from commandline, then you can completely stop the OpenERP server and then try again.
Ray Carnes Thank you. Helped me too. I restarted postgresql.
PostgreSQL Drop Database
we have already created a database in our previous chapter. You can Drop database using either of the following methods:
- OS Command Prompt
- SQL Prompt
1.OS Command Prompt:
- dropdb — remove a PostgreSQL database
- dropdb destroys an existing PostgreSQL database. The user who executes this command must be a database superuser or the owner of the database.
- dropdb is a wrapper around the SQL command DROP DATABASE. There is no effective difference between dropping databases via this utility and via other methods for accessing the server.
Synatax:
dropdb [connection-option...] [option...] dbname
dropdb accepts the following command-line arguments:
|
Options |
Description |
|
dbname |
Specifies the name of the database to be removed. |
|
-e —echo |
Echo the commands that dropdb generates and sends to the server. |
|
-i —interactive |
Issues a verification prompt before doing anything destructive |
|
-V —version |
Print the dropdb version and exit. |
|
-? —help |
Show help about dropdb command line arguments, and exit. |
|
dropdb also accepts the following command-line arguments for connection parameters: |
|
|
-h —host |
Specifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix domain socket. |
|
-p —port |
Specifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. |
|
-U —username |
User name to connect as |
|
-w —no-password |
Never issue a password prompt. If the server requires password authentication and a password is not available by other means such as a .pgpass file, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password. |
|
-W —password |
Force dropdb to prompt for a password before connecting to a database. This option is never essential, since dropdb will automatically prompt for a password if the server demands password authentication. However, dropdb will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing -W to avoid the extra connection attempt. |
Examples:
Following example demonstrates deleting a database from OS command prompt:
To destroy the database demo on the default database server:
$ dropdb demo
First we need to Check what database do you want drop:
postgres=# l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
------------+----------+----------+-------------+-------------+-----------------------
account | u1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
musicdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
sales | u2 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy2 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
(8 rows)
To destroy the database
demo
using the server on host
eden
, port 5000, with verification and a peek at the underlying command:
[postgres@r1 ~]$ dropdb -p 5432 -h r1 -i -e sales
Database "sales" will be permanently removed.
Are you sure? (y/n) Y
Please answer "y" or "n".
Are you sure? (y/n) y
Password:
DROP DATABASE sales;
dropdb: database removal failed: ERROR: database "sales" is being accessed by other users
DETAIL: There is 1 other session using the database.
[postgres@r1 ~]$
solution:
- Above statement throws error becouse database «sales» is being accessed by other users We cannot drop a database that has any open connections/session, including our own connection from psql or pgAdmin III. We must switch to another database or template1 if we want to delete the database we are currently connected to. Thus, it might be more convenient to use the program dropdb instead which is a wrapper around this command.
- another way is we can kill the session using following command
postgres=# SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'sales' AND pid <> pg_backend_pid();
pg_terminate_backend
----------------------
t
(1 row)
after terminated above session you can drop the database:
[root@r1 ~]# dropdb -p 5432 -h r1 -i -e sales
bash: dropdb: command not found
[root@r1 ~]# su - postgres
[postgres@r1 ~]$ dropdb -p 5432 -h r1 -i -e sales
Database "sales" will be permanently removed.
Are you sure? (y/n) y
Password:
DROP DATABASE sales;
[postgres@r1 ~]$
then check database is whether droped or not ollwing command:
postgres=# l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
------------+----------+----------+-------------+-------------+-----------------------
account | u1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
musicdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy2 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
(7 rows)
2.SQL Prompt:
- DROP DATABASE — remove a database
- DROP DATABASE drops a database. It removes the catalog entries for the database and deletes the directory containing the data. It can only be executed by the database owner. Also, it cannot be executed while you or anyone else are connected to the target database. (Connect to postgres or any other database to issue this command.)
- DROP DATABASE cannot be undone. Use it with care
dropdb accepts the following command-line arguments:
|
Options |
Description |
|
IF EXISTS |
Specifies the name of the database to be removed. |
|
-e —echo |
Echo the commands that dropdb generates and sends to the server. |
Notes:
- DROP DATABASE cannot be executed inside a transaction block.
- This command cannot be executed while connected to the target database. Thus, it might be more convenient to use the program dropdb instead, which is a wrapper around this command.
Examples:
First we will check the List of database:
postgres=# l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privile
ges
------------+----------+----------+-------------+-------------+-----------------
------
account | u1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
musicdb | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy2 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
(7 rows)
Drop the «musicdb» database:
postgres=# drop database musicdb;
ERROR: database "musicdb" is being accessed by other users
DETAIL: There is 1 other session using the database.postgres=# SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'musicdb' AND pid <> pg_backend_pid();
pg_terminate_backend
----------------------
t
(1 row)postgres=# drop database musicdb;
DROP DATABASE
Then check database whether droped or not:
postgres=# l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
------------+----------+----------+-------------+-------------+-----------------------
account | u1 | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
temp0copy2 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres
+
| | | | | postgres=CTc/postgres
(6 rows)
Popular posts from this blog
How to find the server is whether standby (slave) or primary(master) in Postgresql replication ?
Method 1 You can check the mode of the server using «pg_controldata». [pgsql@test~]$ pg_controldata /usr/local/pgsql/data84/ Database cluster state: in archive recovery —> This is Standby Database Database cluster state: in production —> This is Production Database [Master] Method 2 You can use pg_is_in_recovery() which returns True if recovery is still in progress(so the server is running in standby mode or slave) postgres=# select pg_is_in_recovery(); pg_is_in_recovery ——————- t (1 row) If Return false so the server is running in primary mode or master postgres=# select pg_is_in_recovery(); pg_is_in_recovery ——————- f (1 row)
How to Return a Result Set from a PostgreSQL Stored Procedure
Both stored procedures and user-defined functions are created with CREATE FUNCTION statement in PostgreSQL. To return one or more result sets (cursors in terms of PostgreSQL), you have to use refcursor return type. Quick Example : — Procedure that returns a single result set (cursor) CREATE OR REPLACE FUNCTION show_cities ( ) RETURNS refcursor AS $$ DECLARE ref refcursor; — Declare a cursor variable BEGIN OPEN ref FOR SELECT city , state FROM cities; — Open a cursor RETURN ref; — Return the cursor to the caller END ; $$ LANGUAGE plpgsql; Overview : Return Multiple Result Sets Cursor Lifetime Until the end of transaction Auto-commit Must be off Transaction must be active so the caller can see a result set Important Note : The cursor remains open until the end of transaction, and since PostgreSQL works
PostgreSQL New version upgrade
In this blog we are going to upgrade the postgresql server from 9.5 to 11.3 . We are upgraded the postgres server by using pg_upgrade utility as well as logical backup method , you can follow anyone of the method . Collect the server details before proceed upgrade activity. Title PostgreSQL VERSION 9.5 PostgreSQL VERSION 11.3 DATA DIRECTORY /data_9.5 /data_11.3 BIN path /opt/postgresql/9.5 /opt/postgresql/11.3 PORT 50000 5432 PREREQUEST : =========== Step 1. Check the application backend connection if any application connected , Disconnect the application from DB server. Below command will be helpful to checking backend connection : template1=# select datname, count(*) from pg_stat_activity group by datname; datname | count ————+——- testdb | 1 template1 | 0 (2 rows) template1=# select datname, numbackends from pg_stat_database; datname | numbackends ————+————- testdb | 1 template1 | 0 templ
How to Get Table Size, Database Size, Indexes Size, schema Size, Tablespace Size, column Size in PostgreSQL Database
In this post, I am sharing few important function for finding the size of database, table and index in PostgreSQL. Finding object size in postgresql database is very important and common. Is it very useful to know the exact size occupied by the object at the tablespace. The object size in the following scripts is in GB. The scripts have been formatted to work very easily with PUTTY SQL Editor. 1. Checking table size excluding table dependency: SELECT pg_size_pretty(pg_relation_size(‘mhrordhu_shk.mut_kharedi_audit’)); pg_size_pretty —————- 238 MB (1 row) 2. Checking table size including table dependency: SELECT pg_size_pretty(pg_total_relation_size(‘mhrordhu_shk.mut_kharedi_audit’)); pg_size_pretty —————- 268 MB (1 row) 3. Finding individual postgresql database size SELECT pg_size_pretty(pg_database_size(‘db_name’)); 4. Finding individual table size for postgresql database -including dependency index: SELECT pg_size_pretty(pg_total_rel
Linux ctime,mtime,atime,cmin,amin,mmin
Unix and therefore Linux uses (at least) 3 different timestamps on modern file systems (see File systems Table for info) in order to date any files. You can use these information to search for files, check logs, manage your backup and more… that’s why it is a must for any sysadmin to clearly understand this mechanism. This page is aimed at exposing basics knowledge to understand and use files timestamps. 1) Definitions Here are some time stamps related definitions. 1.1 atime This is the Access time : atime is updated whenever file’s data is accessed (a read, write or any other access); this could be done by a system process, interactively by CLI or by a script. 1.2 mtime This is the Modification time : mtime is updated whenever the file’s content changes. This time stamp is not updated by a change of files permissions (e.g : through a chown command). It is usually used for tracking the file content changes (see the Linux time related tools section below for more inf
