我是Python的新手,我想使用SQL查询中的值而不是将参数传递到脚本中。该值位于SQL Server数据库中
我通过传递EmployeeID
作为参数来使其工作,所以我只是使用动态SQL来构建Python调用并保存并在.bat文件中运行。
我想添加'Select EmployeeID from ciphr_staging where date_left is null'
作为输入查询,以在URL末尾提供值,并循环查询返回的所有employeeID
。
import json
import pyodbc
import requests
import sys
user = sys.argv[1]
url = "https://someurl.com/api/PersonPhoto/{}".format(user)
headers = {
'Accept': "application/json",
'Authorization': "apikey ekereeerererereerrerererererereere",
'Content-Type': "application/json",
'cache-control': "no-cache"
}
response = requests.request("GET", url, headers=headers)
RTP = response.text
RTP = "{\"PersonPhoto\": [" + RTP + "]}"
data = json.loads(RTP)
ID,Photo,PhotoDate,PhotoType = [],[],[],[]
for device in data['PersonPhoto']:
ID.append(device[u'ID'])
Photo.append(device[u'Photo'])
PhotoDate.append(device[u'PhotoDate'])
PhotoType.append(device[u'PhotoType'])
connStr = pyodbc.connect(
"DRIVER={SQL Server};"
"SERVER=Testme;"
"Database=Intranet;"
"Trusted_Connection=yes;"
)
cursor = connStr.cursor()
sql = "INSERT INTO dbo.Employee_Photo2 ([EmployeeID],[PhotoBinary],[PhotoDate],[FileType]) VALUES (?,?,?,?)"
vals = [(int(device[u'ID']), device[u'Photo'], device[u'PhotoDate'], device[u'PhotoType']) \
for device in data['PersonPhoto']]
cursor.executemany(sql, vals)
connStr.commit()
cursor.close()
connStr.close()