【发布时间】:2021-03-09 19:09:18
【问题描述】:
我正在编写一些代码,这些代码将从 API 中提取数据并将记录插入到我的表中。
我不确定如何格式化我的插入语句。我想在表中不存在匹配项的地方插入值(基于日期),我不想在列反对者 = 我学校的团队的地方插入值。
import datetime
import requests
import cx_Oracle
import os
from pytz import timezone
currentYear = 2020
con = Some_datawarehouse
cursor = con.cursor()
json_obj = requests.get('https://api.collegefootballdata.com/games?year='+str(currentYear)+'&seasonType=regular&team=myteam')\
.json()
for item in json_obj:
EVENTDATE = datetime.datetime.strptime(item['start_date'], '%Y-%m-%dT%H:%M:%S.%fZ').date()
EVENTTIME = str(datetime.datetime.strptime(item['start_date'], '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=timezone('EST')).time())
FINAL_SCORE = item.get("home_points", None)
OPPONENT = item.get("away_team", None)
OPPONENT_FINAL_SCORE = item.get("away_points", None)
cursor.execute('''INSERT INTO mytable(EVENTDATE,EVENTTIME,FINAL_SCORE,OPPONENT,OPPONENT_FINAL_SCORE) VALUES (:1,:2,:3,:4,:5)
WHERE OPPONENT <> 'my team'
AND EVENTDATE NOT EXISTS (SELECT EVENTDATE FROM mytable);''',
[EVENTDATE,EVENTTIME,FINAL_SCORE,OPPONENT,OPPONENT_FINAL_SCORE])
con.commit()
con.close
这可能更像是 ORACLE SQL 而不是 python 问题,但我不确定 cursor.execute 是否可以接受 MERGE 语句。我也认识到 WHERE 语句在这里不起作用,但这更像是我想要完成的一个想法。
【问题讨论】:
-
cx_Oracle 的
execute()接受 Oracle SQL MERGE 语句:您现在可能已经测试过了。 -
关于数据加载的旁注:如果您有多个记录,请确保您使用的是
executemany()。见Batch Statement Execution and Bulk Loading。