Search code examples
pythonpostgresqlpsycopg2

psycopg2.OperationalError: FATAL: database does not exist


I'm trying to populate a couple databases with psycopg2 within a server I am not the root user of (don't know if it's relevant or not). My code looks like

import json
from  psycopg2 import connect

cors = connect(user='jungal01', dbname='course')
req = connect(user="jungal01", dbname='requirement')

core = cors.cursor()
reqs = req.cursor()

with open('gened.json') as gens:
    geneds = json.load(gens)

for i in range(len(geneds)):
    core.execute('''insert into course (number, description, title)
                    values({0}, {1}, {2});''' .format(geneds[i]["number"], geneds[i]['description'], geneds[i]['title'] ))

reqs.execute('''insert into requirement (fulfills)
                values({0});''' .format(geneds[i]['fulfills'] ))
db.commit()

when I execute the code, I get the above pycopg2 error. I know that these particular databases exist, but I just can't figure out why it won't connect to my databases. (side quest, I am also unsure about that commit statement. Should it be in the for loop, or outside of it? It suppose to be database specific?)


Solution

  • First, you have db is not a defined variable, so you code shouldn't run completely anyway.

    \list on this server is a bunch of databases full of usernames, of which my username is one

    Then the following is how you should connect. To a database, not a table, and the regular pattern is to put the database name, and then the user/pass.

    A "schema" is a loose term in relational database. Both tables and databases have schemas, but you seem to be expecting to connect to a table, not a database.

    So, try this code with an attempt at fixing your indentation and SQL injection problem -- See this documentation

    Note that you first must have created the two tables in the database you are connecting to.

    import json
    from  psycopg2 import connect
    
    username = 'jungal01'
    conn = connect(dbname=username, user=username)
    cur = conn.cursor()
    
    with open('gened.json') as gens:
        geneds = json.load(gens)
    
        for g in geneds:
            cur.execute('''insert into course (number, description, title)
                            values(%(number)s, %(description)s, %(title)s);''', g)
    
            cur.execute('''insert into requirement (fulfills)
                        values(%(fulfills)s);''', g)
        conn.commit()