Airflow How to execute query with Oracle Hook

Viewed 2247

i need to execute an update query (Oracle), the query have some parameter from xcom, so i need to use a PythonOperator with a Oracle Hook (i'm not sure but i can't do this with an oracle operator).

I have already do the same with a select query like :

oracle_db = OracleHook(oracle_conn_id)
query = f"SELECT count(1) AS NB FROM mag;"
result = execute_get_first(oracle_db, query) <-- this working well


def execute_get_first(db, query):
  result = None
  try:
      result = db.get_first(query) <-- db.execut() not exist
  except Exception as e:
      logging.error(e)
  return result

my question is for an Oracle Hook, does it exist a method like get_first but for execute a query like update or insert ?

1 Answers

OracleHook inherits from DbApiHook thus all methods of DbApiHook are available to be used including get_first, insert_rows and others.

usage example:

from airflow.decorators import task
from airflow.providers.oracle.hooks.oracle import OracleHook

@task
def task_1():
    hook = OracleHook(oracle_conn_id="oracle_conn_id")
    rows = [
        (
            "something",
            "something2",
        )
    ]
    target_fields = [
        'col',
        'col2',
    ]
    hook.insert_rows('mag', rows, target_fields)
    value = hook.get_first(sql="SELECT count(1) AS NB FROM mag")
    return value
Related