First off, it’s helpful to create a database named the same as your current use, to prevent the error when you just want to use the default database and create new tables without declaring the name of a db explicitly.
Replace «skynotify» with your username:
psql -d postgres -c "CREATE DATABASE skynotify ENCODING 'UTF-8';"
-d explicitly declares which database to use as the default for SQL statements that don’t explicitly include a db name during this interactive session.
BASICS FOR GETTING A CLEAR PICTURE OF WHAT YOUR PostgresQL SERVER has in it.
You must connect to an existing database to use psql interactively. Fortunately, you can ask psql for a list of databases:
psql -l
.
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
----------------------------------+-----------+----------+-------------+-------------+-------------------
skynotify | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
myapp_dev | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
ruby-getting-started_development | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify +
| | | | | skynotify=CTc/skynotify
template1 | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify +
| | | | | skynotify=CTc/skynotify
(6 rows)
This does NOT start the interactive console, it just outputs a text based table to the terminal.
As another answers says, postgres is always created, so you should use it as your failsafe database when you just want to get the console started to work on other databases. If it isn’t there, then list the databases and then use any one of them.
In a similar fashion, select tables from a database:
psql -d postgres -c "\dt;"
My «postgres» database has no tables, but any database that does will output a text based table to the terminal (standard out).
And for completeness, we can select all rows from a table too:
psql -d ruby-getting-started_development -c "SELECT * FROM widgets;"
.
id | name | description | stock | created_at | updated_at
----+------+-------------+-------+------------+------------
(0 rows)
Even if there are zero rows returned, you’ll get the field names.
If your tables have more than a dozen rows, or you’re not sure, it’ll be more useful to start with a count of rows to understand how much data is in your database:
psql -d ruby-getting-started_development -c "SELECT count(*) FROM widgets;"
.
count
-------
0
(1 row)
And don’t that that «1 row» confuse you, it just represents how many rows are returned by the query, but the 1 row contains the count you want, which is 0 in this example.
NOTE: a db created without an owner defined will be owned by the current user.
According to the documentation, so long as I’m not connected to a database, I can either delete a database in the console using:
DROP DATABASE dbname;
Or I can drop it using the wrapper tool dropdb
.
Both give me an error saying the database doesn’t exist, yet when in the console and typing the command \l
, I get a list of databases including the one I want to delete.
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
---------------------------+-----------+----------+-------------+-------------+-----------------------
Blog_development | myusername | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
Blog_test | myusername | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
The database name is Blog_development (and the one below it). I was playing with rails and trying to learn from the online documentation. I wanted to start over and delete everything.
When trying to delete it however, it says it doesn’t exist. I’m brand new to PostgreSQL so I’m a bit lost, nothing in the documentation about this error other than it popping up when it doesn’t exist. Of course it exists, it’s right there.
Following the postgresql installation instructions for Mac, I recently created a db and launched the server. Everything looks like it’s working fine.
/opt/local/lib/postgresql93/bin/postgres -D /opt/local/var/db/postgresql93/defaultdb
LOG: database system was shut down at 2013-08-12 15:36:09 PDT
LOG: database system is ready to accept connections
LOG: autovacuum launcher started
However, when I try to access the database from Python3 Django, I get the following error:
OperationalError: FATAL: database "/opt/local/var/db/postgresql93/defaultdb" does not exist
If I go into that directory, defaultdb, I see that it exists and there are many files in it.
Aside from the above error message appearing in the Python traceback, it also appears in the postgres log:
FATAL: database "defaultdb" does not exist
FATAL: database "/opt/local/var/db/postgresql93/defaultdb" does not exist
I’ve also tried replacing the full path with just the name «defaultdb», but get the same message.
EDIT: In fact, running the following doesn’t work either:
/opt/local/bin/psql93 defaultdb
psql93: FATAL: database "defaultdb" does not exist
Я использую приложение PostgreSql для mac (http://postgresapp.com/). Я использовал его в прошлом на других машинах, но это создавало мне проблемы при установке на моем macbook. Я установил приложение, и я побежал:
psql -h localhost
Он возвращает:
psql: FATAL: database "<user>" does not exist
Кажется, я даже не могу запустить консоль для создания базы данных, которую он пытается найти. То же самое происходит, когда я просто запускаю:
psql
или если я запустил psql из выпадающего меню приложения:
Статистика машины:
-
OSX 10.8.4
-
psql (PostgreSQL) 9.2.4
Любая помощь приветствуется.
Я также попытался установить PostgreSql через homebrew, и я получаю ту же проблему. Я также прочитал страницу документации по приложениям, в которой говорится:
Когда Postgres.app запускается сначала, он создает базу данных USER, которая является базой данных по умолчанию для psql, когда ни один не указан. пользователь по умолчанию — USER, без пароля.
Таким образом, казалось бы, приложение не создает $USER, но я установил- > uninstalled-reinstalled несколько раз, так что это должно быть что-то с моей машиной.
Я нашел ответ, но я точно не знаю, как он работает как пользователь, который ответил на этот поток → Получение Postgresql Running In Mac: Database «postgres» не существует не последовало. Я использовал следующую команду, чтобы открыть psql:
psql -d template1
Я оставлю этого без ответа, пока кто-нибудь не сможет объяснить, почему это работает.
Ответ 1
Похоже, что ваш менеджер пакетов не смог создать базу данных с именем $user для вас. Причина, по которой
psql -d template1
работает для вас, так это то, что template1 — это база данных, созданная самими postgres и присутствующая на всех установках.
Вы, видимо, можете войти в шаблон1, поэтому у вас должны быть определенные права, назначенные вам базой данных. Попробуйте это в командной строке:
createdb
а затем посмотрите, можете ли вы снова войти в систему с помощью
psql -h localhost
Это просто создаст базу данных для вашего пользователя входа, и я думаю, это то, что вы ищете. Если createdb не удалось, у вас недостаточно прав на создание собственной базы данных, и вам придется выяснить, как исправить пакет homebrew.
Ответ 2
В терминале просто запустите команду в окне командной строки. (Не внутри PSQL).
createdb <user>
А затем снова попробуйте запустить postgres.
Ответ 3
По умолчанию postgres пытается подключиться к базе данных с тем же именем, что и ваш пользователь. Чтобы предотвратить это поведение по умолчанию, просто укажите пользователя и базу данных:
psql -U Username DatabaseName
Ответ 4
- Войти как пользователь по умолчанию:
sudo -i -u postgres
- Создать нового пользователя:
createuser --interactive
- При запросе имени роли введите имя пользователя linux и выберите «Да» на вопрос суперпользователя.
- Пока вы вошли в систему как пользователь postgres, создайте базу данных:
createdb <username_from_step_3>
- Подтвердите, что ошибки (-и) исчезли, введя:
psql
в командной строке. - Вывод должен показывать
psql (x.x.x) Type "help" for help.
Ответ 5
Вход с использованием базы данных template1 по умолчанию:
#psql -d template1
#template1=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+---------+----------+-------------+-------------+---------------------
postgres | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca +
| | | | | gogasca=CTc/gogasca
template1 | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca +
| | | | | gogasca=CTc/gogasca
(3 rows)
Создайте базу данных с помощью userId:
template1=# CREATE DATABASE gogasca WITH OWNER gogasca ENCODING 'UTF8';
CREATE DATABASE
Выйти, а затем снова войти в систему
template1=# \q
gonzo:~ gogasca$ psql -h localhost
psql (9.4.0)
Type "help" for help.
gogasca=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+---------+----------+-------------+-------------+---------------------
gogasca | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca +
| | | | | gogasca=CTc/gogasca
template1 | gogasca | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/gogasca +
| | | | | gogasca=CTc/gogasca
(4 rows)
Ответ 6
Я столкнулся с такой же ошибкой, когда пытаюсь открыть postgresql на mac
psql: FATAL: database "user" does not exist
Я нашел эту простую команду для ее решения:
метод1
$ createdb --owner=postgres --encoding=utf8 user
и введите
psql
Способ 2:
psql -d postgres
Ответ 7
Если бы возникла та же проблема, это сделал простой psql -d postgres
(psql -d postgres
команду в терминале)
Ответ 8
Эта ошибка также может возникать, если для переменной среды PGDATABASE установлено имя базы данных, которая не существует.
В OSX я увидел следующую ошибку при попытке запустить psql из меню Postgress.app:
psql: FATAL: database "otherdb" does not exist
Решение этой ошибки заключалось в удалении export PGDATABASE=otherdb
из ~/.bash_profile
:
Кроме того, если для PGUSER установлено значение, отличное от вашего имени пользователя, произойдет следующая ошибка:
psql: FATAL: role "note" does not exist
Решение состоит в удалении export PGUSER=notme
из ~/.bash_profile
.
Ответ 9
Поскольку этот вопрос является первым в результатах поиска, я все равно положу другое решение для другой проблемы, чтобы не иметь дублирующее название.
Такое же сообщение об ошибке может возникнуть при запуске файла запроса в psql
без указания базы данных. Поскольку в postgresql нет инструкции use
, мы должны указать базу данных в командной строке, например:
psql -d db_name -f query_file.sql
Ответ 10
Как показано в createdb documentation:
Первая база данных всегда создается командой initdb, когда область хранения данных инициализируется… Эта база данных называется postgres.
Поэтому, если определенные дистрибутивы OS/postgresql делают это по-другому, это, конечно, не стандарт по умолчанию/стандарт (только что проверено, что initdb
на openSUSE 13.1 создает «postgres» базы данных, но не «<user> » ). Короче говоря, psql -d postgres
, как ожидается, будет использоваться при использовании пользователя, отличного от «postgres».
Очевидно, что принятый ответ, работающий createdb
для создания БД, подобный пользователю, также работает, но создает избыточную БД.
Ответ 11
возникла проблема с использованием драйвера JDBC, поэтому нужно просто добавить базу данных (возможно, избыточно в зависимости от инструмента, который вы можете использовать) после имени хоста в URL-адресе, например.
jdbc:postgres://<host(:port)>/<db-name>
более подробная информация приведена здесь: http://www.postgresql.org/docs/7.4/static/jdbc-use.html#JDBC-CONNECT
Ответ 12
Во-первых, полезно создать базу данных с именем так же, как и текущее использование, чтобы предотвратить ошибку, когда вы просто хотите использовать базу данных по умолчанию и создавать новые таблицы без явного объявления имени db.
Замените «skynotify» своим именем пользователя:
psql -d postgres -c "CREATE DATABASE skynotify ENCODING 'UTF-8';"
-d явно объявляет, какую базу данных использовать в качестве стандартного для операторов SQL, которые явно не включают имя db во время этого интерактивного сеанса.
ОСНОВЫ ДЛЯ ПОЛУЧЕНИЯ ЧИСТОГО ИЗОБРАЖЕНИЯ ЧТО ВАШЕ ПОЛЬЗОВАТЕЛЯ PostgresQL SERVER.
Вы должны подключиться к существующей базе данных для использования psql в интерактивном режиме. К счастью, вы можете запросить psql для списка баз данных:
psql -l
.
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
----------------------------------+-----------+----------+-------------+-------------+-------------------
skynotify | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
myapp_dev | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
ruby-getting-started_development | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify +
| | | | | skynotify=CTc/skynotify
template1 | skynotify | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/skynotify +
| | | | | skynotify=CTc/skynotify
(6 rows)
Это НЕ запускает интерактивную консоль, она просто выводит текстовую таблицу на терминал.
Как говорят другие ответы, postgres всегда создается, поэтому вы должны использовать его как свою отказоустойчивую базу данных, когда просто хотите, чтобы консоль начала работать с другими базами данных. Если его там нет, перечислите базы данных и затем используйте любой из них.
Аналогичным образом выберите таблицы из базы данных:
psql -d postgres -c "\dt;"
В моей базе данных «postgres» нет таблиц, но любая база данных, которая делает, выводит текстовую таблицу на терминал (стандартная версия).
И для полноты мы также можем выбрать все строки из таблицы:
psql -d ruby-getting-started_development -c "SELECT * FROM widgets;"
.
id | name | description | stock | created_at | updated_at
----+------+-------------+-------+------------+------------
(0 rows)
Даже если возвращаются нулевые строки, вы получите имена полей.
Если в ваших таблицах более дюжины строк, или вы не уверены, будет полезно начать с подсчета строк, чтобы понять, сколько данных в вашей базе данных:
psql -d ruby-getting-started_development -c "SELECT count(*) FROM widgets;"
.
count
-------
0
(1 row)
И не то, что «1 строка» вас смущает, она просто представляет количество строк, возвращаемых запросом, но 1 строка содержит нужный вам счет, который равен 0 в этом примере.
ПРИМЕЧАНИЕ. ДБ, созданный без определенного владельца, будет принадлежать текущему пользователю.
Ответ 13
Я попробовал некоторые из этих решений, но они не совсем работали (хотя они были очень на правильном пути!)
В итоге моя ошибка была:
FATAL: аутентификация по паролю не удалась
когда я запустил следующую команду: psql
Итак, я запустил эти две команды:
dropdb()
createdb()
ПРИМЕЧАНИЕ: это приведет к удалению БД, но мне это не нужно, и по какой-то причине я больше не могу получить доступ к pqsl, поэтому я удалил и воссоздал его. Затем psql
снова работал.
Ответ 14
Подключитесь к postgres через существующего суперпользователя.
Создайте базу данных по имени пользователя, через которого вы подключаетесь к postgres.
create database username;
Теперь попробуйте подключиться через имя пользователя
Ответ 15
Попробуйте using-
psql -d postgres
Я также столкнулся с той же проблемой, когда бежал psql
Ответ 16
Если эта проблема возникла при установке postgresql через homebrew.
Пришлось создать суперпользователя по умолчанию «postgres» с помощью:
createuser —interactive postgres ответ y для суперпользователя
createuser — интерактивный пользовательский ответ y для суперпользователя
Ответ 17
У меня все еще была проблема выше, после установки postgresql с помощью homebrew — я разрешил ее, поставив /usr/local/bin на мой путь до/usr/bin
Ответ 18
Если вы получаете эту ошибку при развертывании проекта Rails с Capistrano, вам может понадобиться создать базу данных на удаленном сервере.
Войдите в свой Ubuntu и запустите:
sudo -u postgres psql
Введите пароль пользователя postgres, если появится запрос. Теперь создайте свою базу данных, введя:
CREATE DATABASE dbname_production;
Имя должно быть тем, которое вы указали в shared/config/database.yml
на рабочем сервере.
Выход, введя \q
Ответ 19
В нем простейшее объяснение; это проблема noob. Просто введите
pgres
приведет к этому отклику.
pgres <db_name>
будет успешным без ошибок, если у пользователя есть разрешения на доступ к db.
Можно вдаваться в детали переменных экспортируемой среды, но это необязательно. Это слишком просто для отказа по любой другой причине.
Learn how to solve the common PostgreSQL error psql: FATAL: database «root» does not exist.» New PostgreSQL users often encounter this error when first logging in to PostgreSQL.
Requirements
- A Cloud Server running Linux (any distribution)
- PostgreSQL installed and running
vServer (VPS) from IONOS
Low-cost, powerful VPS hosting for running your custom applications, with a personal assistant and 24/7 support.
100 % SSD storage
Ready in 55 sec.
SSL certificate
Switch to the PostgreSQL user
If you have used MySQL/MariaDB in the past, you may be accustomed to logging into the database with the command mysql -u root -p from any account. However, PostgreSQL uses a different security model.
PostgreSQL has its own user on the system which is created when PostgreSQL is installed. The postgres user is able to log into PostgreSQL without using a password. No other user is able to log into PostgreSQL.
This means that before using PostgreSQL, you will need to switch to that user account with the command:
You will then be able to log into the PosgreSQL client with the command:
You will not be able to access the database from the command line as any other user.
What the error means
When you log into PostgreSQL as any user other than the postgres user, it will attempt to log you into a database of the same name as your user account. This means that if you try to use the psql command as root, it will try to log you into the database root. If you try to log in while signed on as jdoe it will look for the database jdoe, and so forth.
Unable to find this database, PostgreSQL gives the error message that «database [your username] does not exist.»
Related articles
PostgreSQL “Could not connect to server” Error: How to troubleshoot
One of the most common errors that occur when using PostgreSQL is the “Could not connect to server” error that results in a refused connection. Usually, the error can be fixed by taking just a few simple steps. In this article, we will show you how to fix a PostgreSQL that cannot connect to the server in Linux. Read on for more.
PostgreSQL “Could not connect to server” Error: How to troubleshoot
PostgreSQL: a closer look at the object-relational database management system
The PostgreSQL database management system, also known to many as Postgres, has many decades of development behind it. It originally started as a project at Berkeley University in California. Today, the open source database continues to defy solutions from commercial competitors, since the development team is constantly working on its functionality and performance. But what exactly is PostgreSQL?…
PostgreSQL: a closer look at the object-relational database management system