繁体   English   中英

sqlalchemy原始sql查询限制使用connection.execute()

[英]sqlalchemy raw sql query limit using connection.execute()

这个python代码应该在数据库上运行语句,但是不执行sql语句:

from sqlalchemy import *
sql_file = open("test.sql","r")
sql_query = sql_file.read()
sql_file.close()
engine = create_engine(
    'postgresql+psycopg2://user:password@localhost/test', echo=False)

conn = engine.connect()
print sql_query
result = conn.execute(sql_query)
conn.close()

test.sql文件包含创建89个表的SQL语句。

如果我指定89个表,则不会创建表,但是如果我将表的数量减少到2就可以了。

conn.execute中可以执行的查询数量是否有限制? 如何运行这样的任意数量的原始查询?

或许,强制自动提交:

conn.execute(RAW_SQL).execution_options(autocommit=True))

其他方法是使用事务并执行提交:

t = conn.begin()
try:
    conn.execute(RAW_SQL)
    t.commit()
except:
    t.rollback()

PD:您也可以将execution_options放在create_engine参数中。

为什么在SQLAlchemy中使用原始SQL? 如果你没有充分的理由,你应该使用其他方法:

http://docs.sqlalchemy.org/en/rel_0_7/orm/tutorial.html

http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#metadata-describing

暂无
暂无

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

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