python - psycopg2.OperationalError : FATAL: database does not exist

标签 python postgresql psycopg2

我正在尝试在我不是根用户的服务器中使用 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 错误。我知道存在这些特定的数据库,但我就是不明白为什么它无法连接到我的数据库。 (附带任务,我也不确定该提交语句。它应该在 for 循环中还是在循环之外?它应该是特定于数据库的?)

最佳答案

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

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

那么下面是你应该如何连接。对于数据库,而不是表,常规模式是输入数据库名称,然后是用户/密码。

“模式”在关系数据库中是一个松散的术语。表和数据库都有模式,但您似乎期望连接到表,而不是数据库。

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

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

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

关于python - psycopg2.OperationalError : FATAL: database does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43600140/

相关文章:

postgresql - Postgresql 中的意外死锁(使用 psycopg2 时)

python - 从 GAE 数据存储快速提供多个图像

python - pandas 填充数据框中给定的缺失时间间隔

linux - 全新安装后 PostgreSQL "cannot access the server configuration file (...) No such file or directory"

java - 如何通过 JDBC 使用包含问号 "?"的 PostgreSQL JSON(B) 运算符

python - Psycopg2(curr.execute)返回 NONE python

Python Flask 调试记录器在生产环境中导致 500 服务器错误 (Apache)

python - 使用 groupby 和 pandas 数据框中的多列从字符串数据创建条形图

ruby-on-rails - 使用不同的列处理单表继承

python postgres 我可以 fetchall() 100 万行吗?