由于值 (') 中的撇号,向 SQL Server db 发送 API JSON 响应时出错。查看operator_country_lar的第二个 JSON 响应
这是一个示例 API 响应:
json_response= '{
"num_results": 455161,
"results": [
{
"activity_date": "1975-12-01",
"activity_id": "50",
"activity_name": "ORDERED",
"operator_country_lar": "France",
"registered_owner_name": "AIR FRANCE"
},
{
"activity_date": "1974-10-01",
"activity_id": "50",
"activity_name": "ORDERED",
"operator_country_lar": "Korea, Democratic People's Republic of",
"registered_owner_name": "KOREAN AIR LINES"
}
],
"results_this_page": 2,
"status": 200}'
序列化响应并执行:
query = "DECLARE @json nvarchar(max)= "+json_response+" INSERT INTO "+self.database+"([activity_date],[activity_name],[operator_name])
SELECT * FROM OPENJSON(@json, '$.results') WITH (activity_date date, activity_name nchar(25), operator_name nchar(256))"
cursor.execute(query)
cnxn.commit()
第一个实例工作正常,但响应中的第二个设置会引发错误。如何转义撇号或者是否有更准确的方法在 PYTHON 中编写 SQL OPENJSON 语句?