psycopg2.OperationalError: FATAL: database does not exist

psycopg2.OperationalError: FATAL: database does not exist

我正在尝试在我不是根用户的服务器中使用 psycopg2 填充几个数据库(不知道它是否相关)。我的代码看起来像

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()

当我执行代码时,出现上述 pycopg2 错误。我知道存在这些特定的数据库,但我就是不明白为什么它无法连接到我的数据库。 (支线任务,我也不确定那个 commit 语句。它应该在 for 循环中还是在循环之外?它应该是特定于数据库的?)

艾伦,你说:"in postgres, tables are databases."那是绝对错误的。您的错误信息源于这种误解。您想要连接到数据库,并插入到该数据库中存在的 table 中。您正在尝试插入数据库 -- 一个无意义的操作。

首先,您 db 不是已定义的变量,因此您的代码无论如何都不应该 运行。

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

那么下面是您应该如何连接。给一个数据库,不是table,常规模式是放数据库名,然后是user/pass.

A "schema" 是关系数据库中的一个松散术语。 table 和数据库都有架构,但您似乎希望连接到 table,而不是数据库。

因此,尝试使用此代码尝试修复缩进和 SQL 注入问题 -- See this documentation

请注意,您首先必须在要连接的数据库中创建两个 table。

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()

确保您将目录名称作为数据库名称,而不是目录下的模式。

目录令人困惑且完全没有必要。更多详情如下:What's the difference between a catalog and a schema in a relational database?