psycopg2.OperationalError:致命:数据库不存在
我想在服务器中用psycopg2填充几个数据库我不是root用户(不知道它是否相关)。我的代码看起来像psycopg2.OperationalError:致命:数据库不存在
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注入问题,这个代码的企图 - 你首先必须在您连接到数据库中创建两个表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()
Allen,你说:“在postgres中,表是数据库“。这是绝对错误的。你的错误信息是由这种误解造成的。你想连接到一个数据库,并插入到该数据库中存在的表中。你试图插入数据库 - 一个无意义的操作。
确保您将目录名称作为数据库名称,而不是目录下的模式。
目录很混乱,而且没有必要。更多细节如下:What's the difference between a catalog and a schema in a relational database?
尽管这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 – Antimony
'insert into course'?这将是一个**表**,而不是一个**数据库** –
也读了关于SQL注入和如何正确使用'执行'和“参数绑定”..提示:'格式'没有必要 –
@ postgres中的cricket_007,表是数据库。模式保持数据库的,但他们并不是特别必要 – Allen