关于postgresql绑定变量的问题

goh*_*goh 7 python postgresql psycopg2

我在看问题并决定尝试使用绑定变量.我用

sql = 'insert into abc2 (interfield,textfield) values (%s,%s)'
a = time.time()
for i in range(10000):
    #just a wrapper around cursor.execute
    db.executeUpdateCommand(sql,(i,'test'))

db.commit()
Run Code Online (Sandbox Code Playgroud)

sql = 'insert into abc2 (intfield,textfield) values (%(x)s,%(y)s)'
for i in range(10000):
    db.executeUpdateCommand(sql,{'x':i,'y':'test'})

db.commit()
Run Code Online (Sandbox Code Playgroud)

看看两套拍摄的时间,上面似乎没有太大的时差.事实上,第二个需要更长的时间.如果我在某个地方犯了错误,有人可以纠正我吗?在这里使用psycopg2.

nat*_*e c 8

查询在Postgresql中是等效的.

绑定是oracle术语.使用它时将保存查询计划,以便下次执行会更快一些.prepare在Postgres做同样的事情.

http://www.postgresql.org/docs/current/static/sql-prepare.html

psycopg2支持内部'绑定',而不prepare支持cursor.executemany()cursor.execute()

(但不要称它与pg人绑定.称之为准备或者他们可能不知道你的意思:)


Eir*_*Nym 6


重要更新:我已经看到所有python库的源代码连接到FreeBSD端口中的PostgreSQL,并且可以说,只有py-postgresql才能真正准备好语句!但它只是Python 3+.

另外py-pg_queue是实现官方数据库协议的有趣lib(python 2.4+)


你错过了关于准备好的陈述尽可能多的问题的答案."Binded变量"是更好的形式,让我们看看:

sql_q = 'insert into abc (intfield, textfield) values (?, ?)'  # common form 
sql_b = 'insert into abc2 (intfield, textfield) values (:x , :y)' # should have driver and db support
Run Code Online (Sandbox Code Playgroud)

所以你的测试应该是这样的:

sql = 'insert into abc2 (intfield, textfield) values (:x , :y)'
for i in range (10000):
    cur.execute(sql, x=i, y='test')
Run Code Online (Sandbox Code Playgroud)

或这个:

def _data(n):
    for i in range (n):
         yield (i, 'test')
sql = 'insert into abc2 (intfield, textfield) values (? , ?)'    
cur.executemany(sql, _data(10000))
Run Code Online (Sandbox Code Playgroud)

等等.

更新: 我刚刚找到兴趣收件人如何透明地替换SQL查询与准备和使用%(名称)s