2017-04-25 35 views
0

我想在服务器中用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循环中,还是在外循环中?它假设是数据库特定的?)

+0

'insert into course'?这将是一个**表**,而不是一个**数据库** –

+0

也读了关于SQL注入和如何正确使用'执行'和“参数绑定”..提示:'格式'没有必要 –

+0

@ postgres中的cricket_007,表是数据库。模式保持数据库的,但他们并不是特别必要 – Allen

回答

1

首先,你有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() 
+0

。您对此非常感兴趣。这个代码让我摆脱了最初的问题,但是psycopg2说在值的第一个逗号(?,?,?)上有一个语法错误; – Allen

+0

我认为问题是问题。 http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries –

+0

你是最棒的!非常感谢! – Allen

1

Allen,你说:“在postgres中,表是数据库“。这是绝对错误的。你的错误信息是由这种误解造成的。你想连接到一个数据库,并插入到该数据库中存在的表中。你试图插入数据库 - 一个无意义的操作。

相关问题