简体   繁体   English

在sqlalchemy中执行准备好的语句

[英]Execute a prepared statement in sqlalchemy

I have to run 40K requests against a username: 我必须针对用户名运行40K请求:

SELECT * from user WHERE login = :login

It's slow, so I figured I would just use a prepared statement. 它很慢,所以我认为我只会使用一个准备好的语句。

So I do 所以我做

e = sqlalchemy.create_engine(...)
c = e.connect()
c.execute("PREPARE userinfo(text) AS SELECT * from user WHERE login = $1")
r = c.execute("EXECUTE userinfo('bob')")
for x in r:
    do_foo()

But I have a: 但是我有一个:

InterfaceError: (InterfaceError) cursor already closed None None

I don't understand why I get an exception 我不明白为什么我会例外

Not sure how to solve your cursor related error message, but I dont think a prepared staement will solve your performance issue - as long as your using SQL server 2005 or later the execution plan for SELECT * from user WHERE login = $login will already be re-used and there will be no performance gain from the prepared statement. 不确定如何解决与光标相关的错误消息,但是我认为准备工作不会解决您的性能问题-只要您使用SQL Server 2005或更高版本, SELECT * from user WHERE login = $login的执行计划就已经可以重复使用,并且准备好的语句不会提高性能。 I dont know about MySql or other SQL database servers, but I suspect they too have similar optimisations for Ad-Hoc queries that make the prepared statement redundant. 我不了解MySql或其他SQL数据库服务器,但我怀疑它们对Ad-Hoc查询也有类似的优化,使准备好的语句变得多余。

It sounds like the cause of the performance hit is more down to the fact that you are making 40,000 round trips to the database - you should try and rewrite the query so that you are only executing one SQL statement with a list of the login names. 听起来性能下降的原因更多地取决于您要进行40,000次数据库往返的事实-您应该尝试重写查询,以便仅执行一个带有登录名列表的SQL语句。 Am I right in thinking that MySql supports an aray data type? 我认为MySql支持aray数据类型是正确的吗? If it doesnt (or you are using Microsoft SQL) you should look into passing in some sort of delimited list of usernames. 如果没有(或者您正在使用Microsoft SQL),则应考虑传递某种分隔的用户名列表。

From this discussion , it might be a good idea to check your paster debug logs in case there is a better error message there. 通过讨论 ,最好检查粘贴调试日志,以防出现更好的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM