gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:17:22 25 4
gpt4 key购买 nike

我正在尝试在我不是根用户的服务器中使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com