Skip to Main Content

DevOps, CI/CD and Automation

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

cx_Oracle function to return sql result into Python var

epipkoAug 6 2020 — edited Aug 6 2020

db.py

--------------

def connect(db):

    """ Connect to the database """

    try:

        # dsn = cx_Oracle.makedsn(host='MYHOST', sid='DEVPRON', port=1521)

        conn = cx_Oracle.connect(user = dbconfig._USER, password = dbconfig._PWD, dsn = db)

    except cx_Oracle.Error as error:

        raise error

    else:

        cur = conn.cursor()   

   

    return conn, cur

def execute(conn, cur, sql, bindvars=None, commit=False):

    """

    Execute whatever SQL statements are passed to the method;

    commit if specified. Do not specify fetchall() in here as

    the SQL statement may not be a select.

    bindvars is a dictionary of variables you pass to execute.

    """

    try:

        cur.execute(sql, bindvars)

    except cx_Oracle.DatabaseError as e:

        raise e

    if commit:

        cur.commit()

main.py

----------

conn, cur = db.connect('TITAN')

sql = ("""  select max(id) order_id from orders """)

How do I return result of select into a variable in Python ???

max_order_id = db.execute(conn, cur, sql)

Comments

Post Details

Added on Aug 6 2020
1 comment
2,383 views