Enable executing multiple statements while execution via sqlalchemy

后端 未结 3 1252
难免孤独
难免孤独 2020-12-17 16:41

I have a DDL object (create_function_foo) that contains a create function statement. In first line of it I put DROP FUNCTION IF EXISTS foo; but

相关标签:
3条回答
  • 2020-12-17 16:47

    There are some cases where SQLAlchemy does not provide a generic way at accessing some DBAPI functions, such as as dealing with multiple result sets. In these cases, you should deal with the raw DBAPI connection directly.

    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))
    
    0 讨论(0)
  • 2020-12-17 16:56

    Yeah... This seems like a bummer to me. I don't want to use the ORM so the accepted answer didn't work for me.

    I did this instead:

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

    And then this failed for a CREATE function.... YMMV.

    0 讨论(0)
  • 2020-12-17 17:05

    multi=True is a requirement for MySql connector. You can not set this flag passing it to SQLAlchemy methods. Do this:

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

    More info here: http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg30129.html

    0 讨论(0)
提交回复
热议问题