Custom Search

Monday, October 7, 2013

Sqlalchemy How to find connection id associated with a Session



 def find_connection_id(_DBSession, msg=""):
    """
    """
    res1 = _DBSession.connection().execute("SELECT connection_id()")
    if res1:
        conn_id = res1.fetchone()[0]
        print "===%s()===conn_id_1===%s" %(msg, conn_id)
    ###OR
    res2 = DBSession.execute("SELECT connection_id();")
    if res2:
        conn_id = res2.fetchone()[0]
        print "===%s()===conn_id_2===%s" %(msg, conn_id)


Output
=====
===message1===conn_id_1===752
===message2===conn_id_2===752

#######################

def find_connection_id(msg=""):
    """
    """
    _DBSession = globals().get("DBSession")
    if _DBSession:
        res1 = _DBSession.connection().execute("SELECT connection_id()")
        if res1:
            conn_id = res1.fetchone()[0]
            print "===%s===conn_id_1===%s" %(msg, conn_id)


Note:
====
1) transaction.commit() will close all existing DBSessions and connection associated with it.
*transaction.commit()

2) DBSession.query() followed by a transaction.commit() will start a new DBSession and connection.
*transaction.commit()
*DBSession.query()


No comments:

Post a Comment