Enable executing multiple statements while execution via sqlalchemy

后端 未结 3 1253
难免孤独
难免孤独 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))
    

提交回复
热议问题