简体   繁体   English

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

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

This python code should run statements on the database, but the sql statements are not executed: 这个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()

The test.sql file contains SQL statements which create 89 tables. test.sql文件包含创建89个表的SQL语句。

The tables are not created if I specify 89 tables, but if I reduce the number of tables to 2 to it works. 如果我指定89个表,则不会创建表,但是如果我将表的数量减少到2就可以了。

Is there a limit on the number of queries that can be executed within the conn.execute? conn.execute中可以执行的查询数量是否有限制? How do a run any number of raw queries like this? 如何运行这样的任意数量的原始查询?

Perhaps, forcing the autocommit: 或许,强制自动提交:

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

Other approach is using transactions and doing the commit: 其他方法是使用事务并执行提交:

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

PD: You can put the execution_options in the create_engine parameters too. PD:您也可以将execution_options放在create_engine参数中。

Why do you use raw SQL with SQLAlchemy? 为什么在SQLAlchemy中使用原始SQL? If you have no good reason for that, you should use other methods: 如果你没有充分的理由,你应该使用其他方法:

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

http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#metadata-describing 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