class documentation

class Connection(Connectable):

View In Hierarchy

Provides high-level functionality for a wrapped DB-API connection.

This is the SQLAlchemy 1.x.x version of the _engine.Connection class. For the :term:`2.0 style` version, which features some API differences, see _future.Connection.

The _engine.Connection object is procured by calling the _engine.Engine.connect method of the _engine.Engine object, and provides services for execution of SQL statements as well as transaction control.

The Connection object is not thread-safe. While a Connection can be shared among threads using properly synchronized access, it is still possible that the underlying DBAPI connection may not support shared access between threads. Check the DBAPI documentation for details.

The Connection object represents a single DBAPI connection checked out from the connection pool. In this state, the connection pool has no affect upon the connection, including its expiration or timeout state. For the connection pool to properly manage connections, connections should be returned to the connection pool (i.e. connection.close()) whenever the connection is not in use.

Class Method ​_handle​_dbapi​_exception​_noconnection Undocumented
Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Construct a new Connection.
Method ​_autobegin Undocumented
Method ​_autorollback Undocumented
Method ​_begin​_impl Undocumented
Method ​_begin​_twophase​_impl Undocumented
Method ​_branch Return a new Connection which references this Connection's engine and connection; but does not have close_with_result enabled, and also whose close() method does nothing.
Method ​_commit​_impl Undocumented
Method ​_commit​_twophase​_impl Undocumented
Method ​_cursor​_execute Execute a statement + params on the given cursor.
Method ​_exec​_driver​_sql Undocumented
Method ​_execute​_20 Undocumented
Method ​_execute​_clauseelement Execute a sql.ClauseElement object.
Method ​_execute​_compiled Execute a sql.Compiled object.
Method ​_execute​_context Create an .ExecutionContext and execute, returning a _engine.CursorResult.
Method ​_execute​_ddl Execute a schema.DDL object.
Method ​_execute​_default Execute a schema.ColumnDefault object.
Method ​_execute​_function Execute a sql.FunctionElement object.
Method ​_generate​_for​_options define connection method chaining behavior for execution_options
Method ​_handle​_dbapi​_exception Undocumented
Method ​_invalid​_transaction Undocumented
Method ​_invoke​_before​_exec​_event Undocumented
Method ​_is​_autocommit Undocumented
Method ​_log​_debug Undocumented
Method ​_log​_info Undocumented
Method ​_prepare​_twophase​_impl Undocumented
Method ​_release​_savepoint​_impl Undocumented
Method ​_revalidate​_connection Undocumented
Method ​_rollback​_impl Undocumented
Method ​_rollback​_to​_savepoint​_impl Undocumented
Method ​_rollback​_twophase​_impl Undocumented
Method ​_run​_ddl​_visitor run a DDL visitor.
Method ​_safe​_close​_cursor Close the given cursor, catching exceptions and turning into log warnings.
Method ​_savepoint​_impl Undocumented
Method ​_warn​_for​_legacy​_exec​_format Undocumented
Method begin Begin a transaction and return a transaction handle.
Method begin​_nested Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle, assuming an outer transaction is already established.
Method begin​_twophase Begin a two-phase or XA transaction and return a transaction handle.
Method close Close this _engine.Connection.
Method commit​_prepared Undocumented
Method connect Returns a branched version of this _engine.Connection.
Method detach Detach the underlying DB-API connection from its connection pool.
Method exec​_driver​_sql Executes a SQL statement construct and returns a _engine.CursorResult.
Method execute Executes a SQL statement construct and returns a _engine.CursorResult.
Method execution​_options Set non-SQL options for the connection which take effect during execution.
Method get​_execution​_options Get the non-SQL options which will take effect during execution.
Method get​_isolation​_level Return the current isolation level assigned to this _engine.Connection.
Method get​_nested​_transaction Return the current nested transaction in progress, if any.
Method get​_transaction Return the current root transaction in progress, if any.
Method in​_nested​_transaction Return True if a transaction is in progress.
Method in​_transaction Return True if a transaction is in progress.
Method invalidate Invalidate the underlying DBAPI connection associated with this _engine.Connection.
Method recover​_twophase Undocumented
Method rollback​_prepared Undocumented
Method run​_callable Given a callable object or function, execute it, passing a _engine.Connection as the first argument.
Method scalar Executes and returns the first column of the first row.
Method scalars Executes and returns a scalar result set, which yields scalar values from the first column of each row.
Method schema​_for​_object Return the schema name for the given schema item taking into account current schema translate map.
Method transaction Execute the given function within a transaction boundary.
Class Variable ​_is​_future Undocumented
Class Variable ​_sqla​_logger​_namespace Undocumented
Class Variable ​_trans​_context​_manager Undocumented
Instance Variable __branch​_from Undocumented
Instance Variable __can​_reconnect Undocumented
Instance Variable __in​_begin Undocumented
Instance Variable ​_dbapi​_connection Undocumented
Instance Variable ​_echo Undocumented
Instance Variable ​_execution​_options Undocumented
Instance Variable ​_has​_events Undocumented
Instance Variable ​_is​_disconnect Undocumented
Instance Variable ​_reentrant​_error Undocumented
Instance Variable dialect Undocumented
Instance Variable dispatch Undocumented
Instance Variable engine The _engine.Engine instance referred to by this .Connectable.
Instance Variable should​_close​_with​_result Undocumented
Property ​_message​_formatter Undocumented
Property ​_schema​_translate​_map Undocumented
Property ​_still​_open​_and​_dbapi​_connection​_is​_valid Undocumented
Property closed Return True if this connection is closed.
Property connection The underlying DB-API connection managed by this Connection.
Property default​_isolation​_level The default isolation level assigned to this _engine.Connection.
Property info Info dictionary associated with the underlying DBAPI connection referred to by this _engine.Connection, allowing user-defined data to be associated with the connection.
Property invalidated Return True if this connection was invalidated.

Inherited from Connectable:

Method ​_run​_visitor Undocumented
@classmethod
def _handle_dbapi_exception_noconnection(cls, e, dialect, engine):

Undocumented

def __enter__(self):

Undocumented

def __exit__(self, type_, value, traceback):

Undocumented

def __init__(self, engine, connection=None, close_with_result=False, _branch_from=None, _execution_options=None, _dispatch=None, _has_events=None, _allow_revalidate=True):
Construct a new Connection.
def _autobegin(self):

Undocumented

def _autorollback(self):

Undocumented

def _begin_impl(self, transaction):

Undocumented

def _begin_twophase_impl(self, transaction):

Undocumented

def _branch(self):

Return a new Connection which references this Connection's engine and connection; but does not have close_with_result enabled, and also whose close() method does nothing.

Deprecated since version 1.4: the "branching" concept will be removed in SQLAlchemy 2.0 as well as the "Connection.connect()" method which is the only consumer for this.

The Core uses this very sparingly, only in the case of custom SQL default functions that are to be INSERTed as the primary key of a row where we need to get the value back, so we have to invoke it distinctly - this is a very uncommon case.

Userland code accesses _branch() when the connect() method is called. The branched connection acts as much as possible like the parent, except that it stays connected when a close() event occurs.

def _commit_impl(self, autocommit=False):

Undocumented

def _commit_twophase_impl(self, xid, is_prepared):

Undocumented

def _cursor_execute(self, cursor, statement, parameters, context=None):

Execute a statement + params on the given cursor.

Adds appropriate logging and exception handling.

This method is used by DefaultDialect for special-case executions, such as for sequences and column defaults. The path of statement execution in the majority of cases terminates at _execute_context().

def _exec_driver_sql(self, statement, multiparams, params, execution_options, future):

Undocumented

def _execute_20(self, statement, parameters=None, execution_options=_EMPTY_EXECUTION_OPTS):

Undocumented

def _execute_clauseelement(self, elem, multiparams, params, execution_options):
Execute a sql.ClauseElement object.
def _execute_compiled(self, compiled, multiparams, params, execution_options=_EMPTY_EXECUTION_OPTS):

Execute a sql.Compiled object.

TODO: why do we have this? likely deprecate or remove

def _execute_context(self, dialect, constructor, statement, parameters, execution_options, *args, **kw):
Create an .ExecutionContext and execute, returning a _engine.CursorResult.
def _execute_ddl(self, ddl, multiparams, params, execution_options):
Execute a schema.DDL object.
def _execute_default(self, default, multiparams, params, execution_options=_EMPTY_EXECUTION_OPTS):
Execute a schema.ColumnDefault object.
def _execute_function(self, func, multiparams, params, execution_options):
Execute a sql.FunctionElement object.
def _generate_for_options(self):
define connection method chaining behavior for execution_options
def _handle_dbapi_exception(self, e, statement, parameters, cursor, context):

Undocumented

def _invalid_transaction(self):

Undocumented

def _invoke_before_exec_event(self, elem, distilled_params, execution_options):

Undocumented

def _is_autocommit(self):

Undocumented

def _log_debug(self, message, *arg, **kw):

Undocumented

def _log_info(self, message, *arg, **kw):

Undocumented

def _prepare_twophase_impl(self, xid):

Undocumented

def _release_savepoint_impl(self, name):

Undocumented

def _revalidate_connection(self):

Undocumented

def _rollback_impl(self):

Undocumented

def _rollback_to_savepoint_impl(self, name):

Undocumented

def _rollback_twophase_impl(self, xid, is_prepared):

Undocumented

def _run_ddl_visitor(self, visitorcallable, element, **kwargs):

run a DDL visitor.

This method is only here so that the MockConnection can change the options given to the visitor so that "checkfirst" is skipped.

def _safe_close_cursor(self, cursor):
Close the given cursor, catching exceptions and turning into log warnings.
def _savepoint_impl(self, name=None):

Undocumented

def _warn_for_legacy_exec_format(self):

Undocumented

def begin(self):

Begin a transaction and return a transaction handle.

The returned object is an instance of .Transaction. This object represents the "scope" of the transaction, which completes when either the .Transaction.rollback or .Transaction.commit method is called.

Tip

The _engine.Connection.begin method is invoked when using the _engine.Engine.begin context manager method as well. All documentation that refers to behaviors specific to the _engine.Connection.begin method also apply to use of the _engine.Engine.begin method.

Legacy use: nested calls to .begin on the same _engine.Connection will return new .Transaction objects that represent an emulated transaction within the scope of the enclosing transaction, that is:

trans = conn.begin()   # outermost transaction
trans2 = conn.begin()  # "nested"
trans2.commit()        # does nothing
trans.commit()         # actually commits

Calls to .Transaction.commit only have an effect when invoked via the outermost .Transaction object, though the .Transaction.rollback method of any of the .Transaction objects will roll back the transaction.

Tip

The above "nesting" behavior is a legacy behavior specific to :term:`1.x style` use and will be removed in SQLAlchemy 2.0. For notes on :term:`2.0 style` use, see _future.Connection.begin.

See Also

_engine.Connection.begin_nested - use a SAVEPOINT

_engine.Connection.begin_twophase - use a two phase /XID transaction

_engine.Engine.begin - context manager available from _engine.Engine

def begin_nested(self):

Begin a nested transaction (i.e. SAVEPOINT) and return a transaction handle, assuming an outer transaction is already established.

Nested transactions require SAVEPOINT support in the underlying database. Any transaction in the hierarchy may commit and rollback, however the outermost transaction still controls the overall commit or rollback of the transaction of a whole.

The legacy form of _engine.Connection.begin_nested method has alternate behaviors based on whether or not the _engine.Connection.begin method was called previously. If _engine.Connection.begin was not called, then this method will behave the same as the _engine.Connection.begin method and return a .RootTransaction object that begins and commits a real transaction - no savepoint is invoked. If _engine.Connection.begin has been called, and a .RootTransaction is already established, then this method returns an instance of .NestedTransaction which will invoke and manage the scope of a SAVEPOINT.

Tip

The above mentioned behavior of _engine.Connection.begin_nested is a legacy behavior specific to :term:`1.x style` use. In :term:`2.0 style` use, the _future.Connection.begin_nested method instead autobegins the outer transaction that can be committed using "commit-as-you-go" style; see _future.Connection.begin_nested for migration details.

Changed in version 1.4.13: The behavior of _engine.Connection.begin_nested as returning a .RootTransaction if _engine.Connection.begin were not called has been restored as was the case in 1.3.x versions; in previous 1.4.x versions, an outer transaction would be "autobegun" but would not be committed.

See Also

_engine.Connection.begin

_engine.Connection.begin_twophase

def begin_twophase(self, xid=None):

Begin a two-phase or XA transaction and return a transaction handle.

The returned object is an instance of .TwoPhaseTransaction, which in addition to the methods provided by .Transaction, also provides a ~.TwoPhaseTransaction.prepare method.

See Also

_engine.Connection.begin

_engine.Connection.begin_twophase

Parameters
xidthe two phase transaction id. If not supplied, a random id will be generated.
def close(self):

Close this _engine.Connection.

This results in a release of the underlying database resources, that is, the DBAPI connection referenced internally. The DBAPI connection is typically restored back to the connection-holding _pool.Pool referenced by the _engine.Engine that produced this _engine.Connection. Any transactional state present on the DBAPI connection is also unconditionally released via the DBAPI connection's rollback() method, regardless of any .Transaction object that may be outstanding with regards to this _engine.Connection.

After _engine.Connection.close is called, the _engine.Connection is permanently in a closed state, and will allow no further operations.

def commit_prepared(self, xid, recover=False):

Undocumented

@util.deprecated_20(':meth:`.Connection.connect`')
def connect(self, close_with_result=False):

Returns a branched version of this _engine.Connection.

The _engine.Connection.close method on the returned _engine.Connection can be called and this _engine.Connection will remain open.

This method provides usage symmetry with _engine.Engine.connect, including for usage with context managers.

def detach(self):

Detach the underlying DB-API connection from its connection pool.

E.g.:

with engine.connect() as conn:
    conn.detach()
    conn.execute(text("SET search_path TO schema1, schema2"))

    # work with connection

# connection is fully closed (since we used "with:", can
# also call .close())

This _engine.Connection instance will remain usable. When closed (or exited from a context manager context as above), the DB-API connection will be literally closed and not returned to its originating pool.

This method can be used to insulate the rest of an application from a modified state on a connection (such as a transaction isolation level or similar).

def exec_driver_sql(self, statement, parameters=None, execution_options=None):
Executes a SQL statement construct and returns a _engine.CursorResult.
Parameters
statementThe statement str to be executed. Bound parameters must use the underlying DBAPI's paramstyle, such as "qmark", "pyformat", "format", etc.
parameters

represent bound parameter values to be used in the execution. The format is one of: a dictionary of named parameters, a tuple of positional parameters, or a list containing either dictionaries or tuples for multiple-execute support.

E.g. multiple dictionaries:

conn.exec_driver_sql(
    "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)",
    [{"id":1, "value":"v1"}, {"id":2, "value":"v2"}]
)

Single dictionary:

conn.exec_driver_sql(
    "INSERT INTO table (id, value) VALUES (%(id)s, %(value)s)",
    dict(id=1, value="v1")
)

Single tuple:

conn.exec_driver_sql(
    "INSERT INTO table (id, value) VALUES (?, ?)",
    (1, 'v1')
)

Note

The _engine.Connection.exec_driver_sql method does not participate in the _events.ConnectionEvents.before_execute and _events.ConnectionEvents.after_execute events. To intercept calls to _engine.Connection.exec_driver_sql, use _events.ConnectionEvents.before_cursor_execute and _events.ConnectionEvents.after_cursor_execute.

See Also

PEP 249

execution​_optionsUndocumented
def execute(self, statement, *multiparams, **params):
Executes a SQL statement construct and returns a _engine.CursorResult.
Parameters
statement

The statement to be executed. May be one of:

  • a plain string (deprecated)
  • any _expression.ClauseElement construct that is also a subclass of .Executable, such as a _expression.select construct
  • a .FunctionElement, such as that generated by .func, will be automatically wrapped in a SELECT statement, which is then executed.
  • a .DDLElement object
  • a .DefaultGenerator object
  • a .Compiled object
Deprecated since version 2.0: passing a string to _engine.Connection.execute is deprecated and will be removed in version 2.0. Use the _expression.text construct with _engine.Connection.execute, or the _engine.Connection.exec_driver_sql method to invoke a driver-level SQL string.
*multiparamsUndocumented
**paramsUndocumented
multiparams/**params

represent bound parameter values to be used in the execution. Typically, the format is either a collection of one or more dictionaries passed to *multiparams:

conn.execute(
    table.insert(),
    {"id":1, "value":"v1"},
    {"id":2, "value":"v2"}
)

...or individual key/values interpreted by **params:

conn.execute(
    table.insert(), id=1, value="v1"
)

In the case that a plain SQL string is passed, and the underlying DBAPI accepts positional bind parameters, a collection of tuples or individual values in *multiparams may be passed:

conn.execute(
    "INSERT INTO table (id, value) VALUES (?, ?)",
    (1, "v1"), (2, "v2")
)

conn.execute(
    "INSERT INTO table (id, value) VALUES (?, ?)",
    1, "v1"
)

Note above, the usage of a question mark "?" or other symbol is contingent upon the "paramstyle" accepted by the DBAPI in use, which may be any of "qmark", "named", "pyformat", "format", "numeric". See pep-249 for details on paramstyle.

To execute a textual SQL statement which uses bound parameters in a DBAPI-agnostic way, use the _expression.text construct.

Deprecated since version 2.0: use of tuple or scalar positional parameters is deprecated. All params should be dicts or sequences of dicts. Use .exec_driver_sql to execute a plain string with tuple or scalar positional parameters.
def execution_options(self, **opt):

Set non-SQL options for the connection which take effect during execution.

For a "future" style connection, this method returns this same _future.Connection object with the new options added.

For a legacy connection, this method returns a copy of this _engine.Connection which references the same underlying DBAPI connection, but also defines the given execution options which will take effect for a call to execute. As the new _engine.Connection references the same underlying resource, it's usually a good idea to ensure that the copies will be discarded immediately, which is implicit if used as in:

result = connection.execution_options(stream_results=True).\
                    execute(stmt)

Note that any key/value can be passed to _engine.Connection.execution_options, and it will be stored in the _execution_options dictionary of the _engine.Connection. It is suitable for usage by end-user schemes to communicate with event listeners, for example.

The keywords that are currently recognized by SQLAlchemy itself include all those listed under .Executable.execution_options, as well as others that are specific to _engine.Connection.

See Also

_engine.Engine.execution_options

.Executable.execution_options

_engine.Connection.get_execution_options

Parameters
**optUndocumented
autocommit

Available on: Connection, statement. When True, a COMMIT will be invoked after execution when executed in 'autocommit' mode, i.e. when an explicit transaction is not begun on the connection. Note that this is library level, not DBAPI level autocommit. The DBAPI connection will remain in a real transaction unless the "AUTOCOMMIT" isolation level is used.

Deprecated since version 1.4: The "autocommit" execution option is deprecated and will be removed in SQLAlchemy 2.0. See :ref:`migration_20_autocommit` for discussion.
compiled​_cache

Available on: Connection. A dictionary where .Compiled objects will be cached when the _engine.Connection compiles a clause expression into a .Compiled object. This dictionary will supersede the statement cache that may be configured on the _engine.Engine itself. If set to None, caching is disabled, even if the engine has a configured cache size.

Note that the ORM makes use of its own "compiled" caches for some operations, including flush operations. The caching used by the ORM internally supersedes a cache dictionary specified here.

logging​_token

Available on: _engine.Connection, _engine.Engine.

Adds the specified string token surrounded by brackets in log messages logged by the connection, i.e. the logging that's enabled either via the :paramref:`_sa.create_engine.echo` flag or via the logging.getLogger("sqlalchemy.engine") logger. This allows a per-connection or per-sub-engine token to be available which is useful for debugging concurrent connection scenarios.

New in version 1.4.0b2.

See Also

:ref:`dbengine_logging_tokens` - usage example

:paramref:`_sa.create_engine.logging_name` - adds a name to the name used by the Python logger object itself.

isolation​_level

Available on: _engine.Connection.

Set the transaction isolation level for the lifespan of this _engine.Connection object. Valid values include those string values accepted by the :paramref:`_sa.create_engine.isolation_level` parameter passed to _sa.create_engine. These levels are semi-database specific; see individual dialect documentation for valid levels.

The isolation level option applies the isolation level by emitting statements on the DBAPI connection, and necessarily affects the original Connection object overall, not just the copy that is returned by the call to _engine.Connection.execution_options method. The isolation level will remain at the given setting until the DBAPI connection itself is returned to the connection pool, i.e. the _engine.Connection.close method on the original _engine.Connection is called, where an event handler will emit additional statements on the DBAPI connection in order to revert the isolation level change.

Warning

The isolation_level execution option should not be used when a transaction is already established, that is, the _engine.Connection.begin method or similar has been called. A database cannot change the isolation level on a transaction in progress, and different DBAPIs and/or SQLAlchemy dialects may implicitly roll back or commit the transaction, or not affect the connection at all.

Note

The isolation_level execution option is implicitly reset if the _engine.Connection is invalidated, e.g. via the _engine.Connection.invalidate method, or if a disconnection error occurs. The new connection produced after the invalidation will not have the isolation level re-applied to it automatically.

no​_parametersWhen True, if the final parameter list or dictionary is totally empty, will invoke the statement on the cursor as cursor.execute(statement), not passing the parameter collection at all. Some DBAPIs such as psycopg2 and mysql-python consider percent signs as significant only when parameters are present; this option allows code to generate SQL containing percent signs (and possibly other characters) that is neutral regarding whether it's executed by the DBAPI or piped into a script that's later invoked by command line tools.
stream​_results

Available on: Connection, statement. Indicate to the dialect that results should be "streamed" and not pre-buffered, if possible. This is a limitation of many DBAPIs. The flag is currently understood within a subset of dialects within the PostgreSQL and MySQL categories, and may be supported by other third party dialects as well.

schema​_translate​_map

Available on: Connection, Engine. A dictionary mapping schema names to schema names, that will be applied to the :paramref:`_schema.Table.schema` element of each _schema.Table encountered when SQL or DDL expression elements are compiled into strings; the resulting schema name will be converted based on presence in the map of the original name.

New in version 1.1.
def get_execution_options(self):

Get the non-SQL options which will take effect during execution.

New in version 1.3.

See Also

_engine.Connection.execution_options

def get_isolation_level(self):

Return the current isolation level assigned to this _engine.Connection.

This will typically be the default isolation level as determined by the dialect, unless if the :paramref:`.Connection.execution_options.isolation_level` feature has been used to alter the isolation level on a per-_engine.Connection basis.

This attribute will typically perform a live SQL operation in order to procure the current isolation level, so the value returned is the actual level on the underlying DBAPI connection regardless of how this state was set. Compare to the _engine.Connection.default_isolation_level accessor which returns the dialect-level setting without performing a SQL query.

New in version 0.9.9.

See Also

_engine.Connection.default_isolation_level - view default level

:paramref:`_sa.create_engine.isolation_level` - set per _engine.Engine isolation level

:paramref:`.Connection.execution_options.isolation_level` - set per _engine.Connection isolation level

def get_nested_transaction(self):

Return the current nested transaction in progress, if any.

New in version 1.4.
def get_transaction(self):

Return the current root transaction in progress, if any.

New in version 1.4.
def in_nested_transaction(self):
Return True if a transaction is in progress.
def in_transaction(self):
Return True if a transaction is in progress.
def invalidate(self, exception=None):

Invalidate the underlying DBAPI connection associated with this _engine.Connection.

An attempt will be made to close the underlying DBAPI connection immediately; however if this operation fails, the error is logged but not raised. The connection is then discarded whether or not close() succeeded.

Upon the next use (where "use" typically means using the _engine.Connection.execute method or similar), this _engine.Connection will attempt to procure a new DBAPI connection using the services of the _pool.Pool as a source of connectivity (e.g. a "reconnection").

If a transaction was in progress (e.g. the _engine.Connection.begin method has been called) when _engine.Connection.invalidate method is called, at the DBAPI level all state associated with this transaction is lost, as the DBAPI connection is closed. The _engine.Connection will not allow a reconnection to proceed until the .Transaction object is ended, by calling the .Transaction.rollback method; until that point, any attempt at continuing to use the _engine.Connection will raise an ~sqlalchemy.exc.InvalidRequestError. This is to prevent applications from accidentally continuing an ongoing transactional operations despite the fact that the transaction has been lost due to an invalidation.

The _engine.Connection.invalidate method, just like auto-invalidation, will at the connection pool level invoke the _events.PoolEvents.invalidate event.

Parameters
exceptionan optional Exception instance that's the reason for the invalidation. is passed along to event handlers and logging functions.
def recover_twophase(self):

Undocumented

def rollback_prepared(self, xid, recover=False):

Undocumented

@util.deprecated('1.4', 'The :meth:`_engine.Connection.run_callable` method is deprecated and will be removed in a future release. Invoke the callable function directly, passing the Connection.')
def run_callable(self, callable_, *args, **kwargs):

Given a callable object or function, execute it, passing a _engine.Connection as the first argument.

The given *args and **kwargs are passed subsequent to the _engine.Connection argument.

This function, along with _engine.Engine.run_callable, allows a function to be run with a _engine.Connection or _engine.Engine object without the need to know which one is being dealt with.

def scalar(self, object_, *multiparams, **params):

Executes and returns the first column of the first row.

The underlying result/cursor is closed after execution.

def scalars(self, object_, *multiparams, **params):

Executes and returns a scalar result set, which yields scalar values from the first column of each row.

This method is equivalent to calling _engine.Connection.execute to receive a _result.Result object, then invoking the _result.Result.scalars method to produce a _result.ScalarResult instance.

New in version 1.4.24.
Returns
a _result.ScalarResult
def schema_for_object(self, obj):
Return the schema name for the given schema item taking into account current schema translate map.
@util.deprecated('1.4', 'The :meth:`_engine.Connection.transaction` method is deprecated and will be removed in a future release. Use the :meth:`_engine.Engine.begin` context manager instead.')
def transaction(self, callable_, *args, **kwargs):

Execute the given function within a transaction boundary.

The function is passed this _engine.Connection as the first argument, followed by the given *args and **kwargs, e.g.:

def do_something(conn, x, y):
    conn.execute(text("some statement"), {'x':x, 'y':y})

conn.transaction(do_something, 5, 10)

The operations inside the function are all invoked within the context of a single .Transaction. Upon success, the transaction is committed. If an exception is raised, the transaction is rolled back before propagating the exception.

Note

The .transaction method is superseded by the usage of the Python with: statement, which can be used with _engine.Connection.begin:

with conn.begin():
    conn.execute(text("some statement"), {'x':5, 'y':10})

As well as with _engine.Engine.begin:

with engine.begin() as conn:
    conn.execute(text("some statement"), {'x':5, 'y':10})

See Also

_engine.Engine.begin - engine-level transactional context

_engine.Engine.transaction - engine-level version of _engine.Connection.transaction

_is_future: bool =

Undocumented

_sqla_logger_namespace: str =

Undocumented

_trans_context_manager =

Undocumented

__branch_from =

Undocumented

__can_reconnect: bool =

Undocumented

__in_begin: bool =

Undocumented

_dbapi_connection =

Undocumented

_echo =

Undocumented

_execution_options =

Undocumented

_has_events =

Undocumented

_is_disconnect =

Undocumented

_reentrant_error: bool =

Undocumented

dialect =

Undocumented

dispatch =

Undocumented

engine =

The _engine.Engine instance referred to by this .Connectable.

May be self if this is already an _engine.Engine.

should_close_with_result: bool =

Undocumented

@util.memoized_property
_message_formatter =

Undocumented

@property
_schema_translate_map =

Undocumented

@property
_still_open_and_dbapi_connection_is_valid =

Undocumented

@property
closed =
Return True if this connection is closed.
@property
connection =

The underlying DB-API connection managed by this Connection.

This is a SQLAlchemy connection-pool proxied connection which then has the attribute _pool._ConnectionFairy.dbapi_connection that refers to the actual driver connection.

@property
default_isolation_level =

The default isolation level assigned to this _engine.Connection.

This is the isolation level setting that the _engine.Connection has when first procured via the _engine.Engine.connect method. This level stays in place until the :paramref:`.Connection.execution_options.isolation_level` is used to change the setting on a per-_engine.Connection basis.

Unlike _engine.Connection.get_isolation_level, this attribute is set ahead of time from the first connection procured by the dialect, so SQL query is not invoked when this accessor is called.

New in version 0.9.9.

See Also

_engine.Connection.get_isolation_level - view current level

:paramref:`_sa.create_engine.isolation_level` - set per _engine.Engine isolation level

:paramref:`.Connection.execution_options.isolation_level` - set per _engine.Connection isolation level

@property
info =

Info dictionary associated with the underlying DBAPI connection referred to by this _engine.Connection, allowing user-defined data to be associated with the connection.

The data here will follow along with the DBAPI connection including after it is returned to the connection pool and used again in subsequent instances of _engine.Connection.

@property
invalidated =
Return True if this connection was invalidated.