Forum Stats

  • 3,760,308 Users
  • 2,251,683 Discussions
  • 7,871,056 Comments

Discussions

cx_Oracle function to return sql result into Python var

epipko
epipko Member Posts: 101 Blue Ribbon
edited Aug 6, 2020 7:05PM in Python

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)

Answers