Dropdb postgresql linux force

How to drop PostgreSQL database through command line [closed]

I’m trying to drop my database and create a new one through the command line. I log in using psql -U username and then do a \connect template1 , followed by a DROP DATABASE databasename; . I get the error

I shut down Apache and tried this again, but I’m still getting this error. Am I doing something wrong?

This will restart postgres and disconnect everyone: sudo service postgresql restart Then do a: dropdb -h localhost -p 5432 -U «youruser» «testdb» Notice the «» to make sure special characters go in without a hitch.

4 Answers 4

You can run the dropdb command from the command line:

Note that you have to be a superuser or the database owner to be able to drop it.

You can also check the pg_stat_activity view to see what type of activity is currently taking place against your database, including all idle processes.

SELECT * FROM pg_stat_activity WHERE datname='database name'; 

Note that from PostgreSQL v13 on, you can disconnect the users automatically with

DROP DATABASE dbname WITH (FORCE); 

This will restart postgres and disconnect everyone: sudo service postgresql restart Then do a: dropdb -h localhost -p 5432 -U «youruser» «testdb» Notice the «» to make sure special characters go in without a hitch.

select pg_terminate_backend(pid) from pg_stat_activity where datname='YourDatabase'; 

for postgresql earlier than 9.2 replace pid with procpid

DROP DATABASE "YourDatabase"; 

Had to change it a bit to work: select pg_terminate_backend(pid) from pg_stat_activity where datname=’YourDatabase’;

Hm. Ran this, but it just reconnected immediately, after saying, «SSL connection closed unexpectedly [. ] attempting to reset: Succeeded.» Annnd, I’m back.

Try this. Note there’s no database specified — it just runs «on the server»

psql -U postgres -c "drop database databasename" 

If that doesn’t work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts; 

then for every id you see, run this:

Sorry I am new to databases, so this is probably a stupid question, but where do I type this out? Before logging into the database right? And I should replace databasename with the name of my database right?

There’s no such things as «just on the server» for postgresql. You must connect to a database. In this case you’ll be connecting to the postgres database which is pretty much there just for cases like this. And a good point on prepared transactions, but in that case you should get an error message saying that’s the issue.

Sorry Bohemian, but you are the one who’s wrong. Here’s pg_stat_activity while running createdb from the command line: postgres=# select * from pg_stat_activity ; 11564 | postgres | 22223 | 16384 | smarlowe | CREATE DATABASE test; | f | 2011-08-19 16:18:26.918933-06 | 2011-08-19 16:18:26.918933-06 | 2011-08-19 16:18:26.916578-06 | | -1 Note that this happens while running createdb from the command line in another terminal. That first field is the db that my createdb script was connected to

Читайте также:  Как активировать суперпользователя в linux

note this does not work for Amazon RDS. It boots you from the psql connection and performs an automatic reset and then you log back in and you’re back to where you started.

When it says users are connected, what does the query «select * from pg_stat_activity;» say? Are the other users besides yourself now connected? If so, you might have to edit your pg_hba.conf file to reject connections from other users, or shut down whatever app is accessing the pg database to be able to drop it. I have this problem on occasion in production. Set pg_hba.conf to have a two lines like this:

local all all ident host all all 127.0.0.1/32 reject 

and tell pgsql to reload or restart (i.e. either sudo /etc/init.d/postgresql reload or pg_ctl reload) and now the only way to connect to your machine is via local sockets. I’m assuming you’re on linux. If not this may need to be tweaked to something other than local / ident on that first line, to something like host . yourusername.

Now you should be able to do:

psql postgres drop database mydatabase; 

Источник

Dropdb postgresql linux force

dropdb — remove a PostgreSQL database

Synopsis

dropdb [ connection-option . ] [ option . ] dbname

Description

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.

Options

dropdb accepts the following command-line arguments:

Specifies the name of the database to be removed.

Echo the commands that dropdb generates and sends to the server.

Attempt to terminate all existing connections to the target database before dropping it. See DROP DATABASE for more information on this option.

Issues a verification prompt before doing anything destructive.

Print the dropdb version and exit.

Do not throw an error if the database does not exist. A notice is issued in this case.

Show help about dropdb command line arguments, and exit.

dropdb also accepts the following command-line arguments for connection parameters:

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.

Specifies the TCP port or local Unix domain socket file extension on which the server is listening for connections.

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.

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.

Читайте также:  How to find executables in linux

Specifies the name of the database to connect to in order to drop the target database. If not specified, the postgres database will be used; if that does not exist (or is the database being dropped), template1 will be used. This can be a connection string. If so, connection string parameters will override any conflicting command line options.

Environment

Default connection parameters

Specifies whether to use color in diagnostic messages. Possible values are always , auto and never .

This utility, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 34.15).

Diagnostics

In case of difficulty, see DROP DATABASE and psql for discussions of potential problems and error messages. The database server must be running at the targeted host. Also, any default connection settings and environment variables used by the libpq front-end library will apply.

Examples

To destroy the database demo on the default database server:

To destroy the database demo using the server on host eden , port 5000, with verification and a peek at the underlying command:

$ dropdb -p 5000 -h eden -i -e demo Database "demo" will be permanently deleted. Are you sure? (y/n) y DROP DATABASE demo; 

See Also

Submit correction

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.

Copyright © 1996-2023 The PostgreSQL Global Development Group

Источник

Dropdb postgresql linux force

DROP DATABASE — удалить базу данных

Синтаксис

DROP DATABASE [ IF EXISTS ] имя [ [ WITH ] ( параметр [, . ] ) ] Здесь допускается параметр: FORCE

Описание

Команда DROP DATABASE удаляет базу данных. Она удаляет из системного каталога записи, относящиеся к базе, а также удаляет с диска каталог, содержащий данные. Выполнить её может только владелец базы данных. Кроме того, нельзя удалить базу, к которой вы подключены в данный момент. (Чтобы выполнить эту команду, подключитесь к postgres или любой другой базе данных.) Также команда не будет выполнена, когда к целевой базе подключены какие-то ещё пользователи, если вы не добавите указание FORCE , описанное ниже.

Действие команды DROP DATABASE нельзя отменить. Используйте её с осторожностью!

Параметры

Не считать ошибкой, если база данных не существует. В этом случае будет выдано замечание. имя

Имя базы данных, подлежащей удалению. FORCE

Попытаться принудительно завершить все существующие подключения к целевой базе данных. Подключения не завершаются, если в целевой базе имеются подготовленные транзакции, активные слоты логической репликации или подписки.

Операция не будет выполнена, если у текущего пользователя нет прав для завершения других подключений, то есть тех же прав, что требуются для выполнения pg_terminate_backend (они описаны в Подразделе 9.27.2). Также произойдёт ошибка, если завершить подключения не удастся.

Замечания

DROP DATABASE нельзя выполнять внутри блока транзакции.

Эту команду нельзя выполнить, если установлено подключение к удаляемой базе данных. Поэтому может быть удобнее вместо неё использовать программу dropdb , которая сама вызывает эту команду внутри.

Читайте также:  Kali linux смена пароля root

Совместимость

Оператор DROP DATABASE отсутствует в стандарте SQL.

См. также

Источник

Dropdb postgresql linux force

dropdb — удалить базу данных PostgreSQL

Синтаксис

dropdb [ параметр-подключения . ] [ параметр . ] имя_бд

Описание

dropdb удаляет ранее созданную базу данных PostgreSQL , и должна выполняться от имени суперпользователя или её владельца.

dropdb это обёртка для SQL -команды DROP DATABASE . Удаление баз данных с её помощью по сути не отличается от выполнения того же действия при обращении к серверу другими способами.

Параметры

dropdb принимает в качестве аргументов:

Указывает имя удаляемой базы данных. -e
—echo

Вывести команды к серверу, генерируемые при выполнении dropdb . -f
—force

Попытаться принудительно завершить все существующие подключения к целевой базе, прежде чем удалять её. Подробнее это описано в DROP DATABASE . -i
—interactive

Выводит вопрос о подтверждении перед удалением. -V
—version

Выводит версию dropdb . —if-exists

Не считать ошибкой, если база данных не существует. В этом случае будет выдано замечание. -?
—help

Вывести справку по команде dropdb .

dropdb также принимает из командной строки параметры подключения:

Указывает имя компьютера, на котором работает сервер. Если значение начинается с косой черты, оно определяет каталог Unix-сокета. -p порт
—port= порт

Указывает TCP-порт или расширение файла локального Unix-сокета, через который сервер принимает подключения. -U имя_пользователя
—username= имя_пользователя

Имя пользователя, под которым производится подключение. -w
—no-password

Не выдавать запрос на ввод пароля. Если сервер требует аутентификацию по паролю и пароль не доступен с помощью других средств, таких как файл .pgpass , попытка соединения не удастся. Этот параметр может быть полезен в пакетных заданиях и скриптах, где нет пользователя, который вводит пароль. -W
—password

Принудительно запрашивать пароль перед подключением к базе данных.

Это несущественный параметр, так как dropdb запрашивает пароль автоматически, если сервер проверяет подлинность по паролю. Однако чтобы понять это, dropdb лишний раз подключается к серверу. Поэтому иногда имеет смысл ввести -W , чтобы исключить эту ненужную попытку подключения. —maintenance-db= имя_бд

Указывает имя опорной базы данных, к которой будет произведено подключение для удаления целевой. Если имя не указано, будет выбрана база postgres , а если она не существует (или именно она и удаляется) — template1 . Здесь может задаваться строка подключения. В этом случае параметры в строке подключения переопределяют одноимённые параметры, заданные в командной строке.

Переменные окружения

Параметры подключения по умолчанию PG_COLOR

Выбирает вариант использования цвета в диагностических сообщениях. Возможные значения: always (всегда), auto (автоматически) и never (никогда).

Эта утилита, как и большинство других утилит PostgreSQL , также использует переменные среды, поддерживаемые libpq (см. Раздел 34.15).

Диагностика

В случае возникновения трудностей, обратитесь к DROP DATABASE и psql . При диагностике следует учесть, что при запуске утилиты также применяются переменные окружения и параметры подключения по умолчанию libpq .

Примеры

Для удаления базы данных demo на сервере, используемом по умолчанию:

Для удаления базы данных demo на сервере eden , слушающим подключения на порту 5000, в интерактивном режиме и выводом запросов к серверу:

$ dropdb -p 5000 -h eden -i -e demo База данных "demo" будет удалена навсегда. Продолжить? (y/n) y DROP DATABASE demo; 

См. также

Источник

Оцените статью
Adblock
detector