关于postgresql绑定变量的问题
-
27-09-2019 - |
题
我正在看 问题 并决定尝试使用绑定变量。我用
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()
和
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()
从上面两组所用的时间来看,似乎时间差距并不大。事实上,第二个需要更长的时间。如果我在某个地方犯了错误,有人可以纠正我吗?在这里使用 psycopg2。
解决方案
在查询在PostgreSQL等效。
绑定为oracle隐语。当你使用它会保存查询计划,以便在下一次执行会快一点。 prepare
做同样的事情在Postgres的。
http://www.postgresql.org/docs/current/静态/ SQL-prepare.html
psycopg2支撑一个内部 '绑定',不与prepare
和cursor.executemany()
cursor.execute()
(但不要将其调用bind到PG人们称它为准备或他们可能不知道你的意思。)
其他提示
重要UPDATE 强>: 我见过纳入所有Python库的源连接到PostgreSQL在FreeBSD的港口,可以说,只有 PY-的PostgreSQL 做真正准备好的发言!但它的Python 3+仅
也PY-pg_queue是有趣的lib实施正式DB协议(蟒2.4 +)
您已经错过了回答有关准备语句中使用尽可能多的这个问题。 “绑定变量”是这更好的形式,让我们来看看:
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
所以测试应该是这样的:
sql = 'insert into abc2 (intfield, textfield) values (:x , :y)'
for i in range (10000):
cur.execute(sql, x=i, y='test')
或这样的:
def _data(n):
for i in range (n):
yield (i, 'test')
sql = 'insert into abc2 (intfield, textfield) values (? , ?)'
cur.executemany(sql, _data(10000))
等。
<强>更新强> 我只是发现兴趣reciple 如何透明地与制备并用%(名称)的使用小号
替换SQL查询不隶属于 StackOverflow