sqlalchemy raw sql query limit using connection.execute()

坚强是说给别人听的谎言 提交于 2021-02-16 06:25:49

问题


This python code should run statements on the database, but the sql statements are not executed:

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.

The tables are not created if I specify 89 tables, but if I reduce the number of tables to 2 to it works.

Is there a limit on the number of queries that can be executed within the conn.execute? How do a run any number of raw queries like this?


回答1:


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.




回答2:


Why do you use raw SQL with SQLAlchemy? 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/core/schema.html#metadata-describing



来源:https://stackoverflow.com/questions/11222223/sqlalchemy-raw-sql-query-limit-using-connection-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!