how to set autocommit = 1 in a sqlalchemy.engine.Connection

后端 未结 5 2194
旧巷少年郎
旧巷少年郎 2021-02-20 00:01

In sqlalchemy, I make the connection:

 conn = engine.connect()

I found this will set autocommit = 0 in my mysqld log. Now I want to set autocom

相关标签:
5条回答
  • 2021-02-20 00:15

    In case you're configuring sqlalchemy for a python application using flask / django, you can create the engine like this:

    # Configure the SqlAlchemy part of the app instance
    app.config['SQLALCHEMY_DATABASE_URI'] = conn_url
    
    
    session_options = {
        'autocommit': True
    }
    
    # Create the SqlAlchemy db instance
    db = SQLAlchemy(app, session_options=session_options)
    
    0 讨论(0)
  • 2021-02-20 00:20

    You can use this:

    from sqlalchemy.sql import text
    
    engine = create_engine(host, user, password, dbname)
    engine.execute(text(sql).execution_options(autocommit=True))
    
    0 讨论(0)
  • 2021-02-20 00:21

    What is your dialect for mysql connection?

    You can set the autocommit to True to solve the problem, like this mysql+mysqldb://user:password@host:port/db?charset=foo&autocommit=true

    0 讨论(0)
  • 2021-02-20 00:25

    From The SQLAlchemy documentation: Understanding autocommit

    conn = engine.connect()
    conn.execute("INSERT INTO users VALUES (1, 'john')")  # autocommits
    

    The “autocommit” feature is only in effect when no Transaction has otherwise been declared. This means the feature is not generally used with the ORM, as the Session object by default always maintains an ongoing Transaction.

    Full control of the “autocommit” behavior is available using the generative Connection.execution_options() method provided on Connection, Engine, Executable, using the “autocommit” flag which will turn on or off the autocommit for the selected scope. For example, a text() construct representing a stored procedure that commits might use it so that a SELECT statement will issue a COMMIT:

    engine.execute(text("SELECT my_mutating_procedure()").execution_options(autocommit=True))
    
    0 讨论(0)
  • 2021-02-20 00:33

    This can be done using the autocommit option in the execution_option() method:

    engine.execute("UPDATE table SET field1 = 'test'").execution_options(autocommit=True))
    

    This information is available within the documentation on Autocommit

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