python - 使用 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)
解决方案
使用绑定变量。像这样的东西:
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 语句中。
(强调我的)
推荐阅读
- java - 如何扩展 Collectors 类
- java - Java中用于整数对组合的switch case实现
- c++ - 无法退出for循环,貌似卡住了
- python - 使用 python 魔杖的图像合成结果不正确
- javascript - onekeydown 在 Firefox 65.0 ubuntu 18.04 中为每次键盘按下返回“进程”字符串
- php - PHP 打印数组值而不需要所有额外的“=>”东西
- azure-devops - 使用 GitPullRequestCompletionOptions 对 Azure DevOps 拉取请求执行 Squash 合并
- excel - 当单元格为空白时,使用带有索引匹配的 If 语句来查看工作簿
- javascript - Select2:如何从 ajax 获得其他响应?
- javascript - 如何在特定模型属性内容的html中用新行替换分号?