通过sqlalchemy执行时启用执行多个语句

时间:2013-11-05 06:56:54

标签: python mysql sqlalchemy

我有一个包含create function语句的DDL对象(create_function_foo)。在第一行中我添加DROP FUNCTION IF EXISTS foo;engine.execute(create_function_foo)返回:

sqlalchemy.exc.InterfaceError: (InterfaceError) Use multi=True when executing multiple statements

我将multi=True作为create_engineengine.execute_optionsengine.execute的参数,但它不起作用。

注意engine如果我的create_engine实例

注意:我正在使用python 3.2 + mysql.connector 1.0.12 + sqlalchemy 0.8.2

create_function_foo = DDL("""\
DROP FUNCTION IF EXISTS foo;
CREATE FUNCTION `foo`(
    SID INT
) RETURNS double
READS SQL DATA
BEGIN
  ...
END
""")

我应该把它放在哪里?

3 个答案:

答案 0 :(得分:10)

multi=True是MySql连接器的要求。您无法设置此标志将其传递给SQLAlchemy方法。这样做:

conn  = session.connection().connection
cursor = conn.cursor()  # get mysql db-api cursor
cursor.execute(sql, multi=True)

此处有更多信息:http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg30129.html

答案 1 :(得分:0)

在某些情况下,SQLAlchemy无法提供访问某些DBAPI函数的通用方法,例如处理多个结果集。在这种情况下,您应该直接处理原始DBAPI连接。

From SQLAlchemy documentation

connection = engine.raw_connection()
try:
    cursor = connection.cursor()
    cursor.execute("select * from table1; select * from table2")
    results_one = cursor.fetchall()
    cursor.nextset()
    results_two = cursor.fetchall()
    cursor.close()
finally:
    connection.close()

You can also do the same using mysql connector as seen here:

operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation, multi=True):
  if result.with_rows:
    print("Rows produced by statement '{}':".format(
      result.statement))
    print(result.fetchall())
  else:
    print("Number of rows affected by statement '{}': {}".format(
      result.statement, result.rowcount))

答案 2 :(得分:0)

是的...在我看来这真是个无赖。我不想使用ORM,因此接受的答案对我不起作用。

我改为这样做:

with open('sql_statements_file.sql') as sql_file:
    for statement in sql_file.read().split(';'):
        if len(statement.strip()) > 0:
             connection.execute(statement + ';')

然后这对于CREATE函数失败。。。YMMV。