pythonpostgresqlpsycopg2dbconnection

Error in database connection: Database "dbname" does not exist


I have created a python file app.py and included the code to connect to a db I created in postgresql as follows: -

import psycopg2

conn = psycopg2.connect(
    user='postgres',
    password='1234',
    host='localhost',
    port='5432',
    database='bubbleformation'  
)

cursor = conn.sursor()
cursor.execute('SELECT * FROM bubbleformation')

for row in cursor: print(row)
conn.close()

This was as instructed in this medium article

However, when I try to execute this python file in the terminal, I get the below error: -

Traceback (most recent call last): File "app.py", line 8, in port='5432' File "/usr/lib/python2.7/dist-packages/psycopg2/init.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: database "bubbleformation" does not exist

I have created a table named "bubbleformation" and it can be viewed in the psql mode through the terminal.

Could anyone please help me understand what should be done? I tried changing the password, and user privileges, but none of them worked for my error.


Solution

  • You should create both database and table with the same name "bubbleformation". You've probably created that table in postgres database.

    Enter psql as postgres user and call CREATE DATABASE bubbleformation;, then connect to it with \connect bubbleformation and then create your table (something like CREATE TABLE bubbleformation (id int, name text);).