首页 > 解决方案 > 使用 python、Airflow 将字节插入 Oracle 表

问题描述

我想使用 Python 将类型(字节)的数据插入到 Oracle 表中的 raw(16) 列中。

INFO - 这是我要插入的数据:

('1', "'test'", "to_date('2021-09-28 15:31:02','YYYY-MM-DD HH24:MI:SS')", b'\xb5V\xad\x04E \xd3V\x1b\x04B\xedL]~W\xf5')

但我有错误

sql = f"INSERT /*+ APPEND */ INTO {table} {target_fields} VALUES  ({','.join(values)})"
    

类型错误:序列项 3:预期的 str 实例,找到的字节

这是我的代码:

def get_md5(d):
       b = pickle.dumps(d)
        return hashlib.md5(b).digest()
    
for row in rows:
    i += 1
    lst = []
    for cell in row:
        if isinstance(cell, str):
            lst.append("'" + str(cell).replace("'", "''") + "'")
        elif cell is None:
            lst.append('NULL')
        elif isinstance(cell, float) and numpy.isnan(cell):  # coerce numpy NaN to NULL
            lst.append('NULL')
        elif isinstance(cell, numpy.datetime64):
            lst.append("'" + str(cell) + "'")
        elif isinstance(cell, datetime):
            lst.append(
                "to_date('" + cell.strftime('%Y-%m-%d %H:%M:%S') + "','YYYY-MM-DD HH24:MI:SS')"
            )
        else:
            lst.append(str(cell))
    lst.append("to_date('" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "','YYYY-MM-DD HH24:MI:SS')")
    s = get_md5(lst)
    lst.append(s)
    
    values = tuple(lst)

    print('values', values)
    sql = f"INSERT /*+ APPEND */ INTO {table} {target_fields} VALUES  ({','.join(values)})"
    print(sql)
    cur.execute(sql)

标签: pythonoraclebyteairflowcx-oracle

解决方案


使用绑定变量。像这样的东西:

def get_md5(d):
       b = pickle.dumps(d)
        return hashlib.md5(b).digest()
    
for row in rows:
    i += 1
    lst = [cell for cell in row]
    lst.append(get_md5(lst))
    
    print('values', lst)

    sql = (
        f"INSERT /*+ APPEND */ INTO {table} {target_fields}"
        f" VALUES ({','.join([f':{field}' for field in target_fields])})"
    )

    print(sql)

    cur.execute(sql, lst)

正如链接文档所述:

使用绑定变量对于可伸缩性和安全性很重要。它们有助于避免 SQL 注入安全问题,因为数据永远不会被视为可执行语句的一部分。切勿将用户数据连接或插入到 SQL 语句中。

(强调我的)


推荐阅读