Python PYODBC与OpenJson问题

问题描述 投票:0回答:1

我试图在我的Python脚本中运行下面的代码,但它却因为语法错误而失败,我一直无法纠正。第一条插入语句从一个网站引入了json数据,并完美地运行。第二条插入语句将json代码格式化,并将其放入另一个SQL表中。这段代码在MSSQL中工作得很好。第二个插入语句提到缺少结束引号,但我似乎有一个开头和结束引号。它还提到一个未解决的引用openjson和未解决的引用cross apply。我试过在insert和select语句周围加上openclosing括号,但没有成功。我查看了github上的pyodbc wiki,但没有看到类似的例子。我在这里做错了什么?谢谢。

cursor.execute("Insert Into InboundJson (json) values (?)", (json.dumps(response_json),))
conn.commit()  -- works fine

cursor = conn.cursor()
cursor.execute("Insert into [CCSBC-DW1].[SurveyMonkey].[dbo].Surveylist (SurveyId, Description, WebSite)

Select J_open.*
from
  dbo.InboundJson j
  cross apply
  openjson(j.[json], '$.data') with ( id          int ,
                                      title  varchar(200),

                                      href    varchar(200)) j_open;")
conn.commit()```




python sql sql-server pyodbc
1个回答
1
投票

多行字符串使用三引号括号即可。

cursor.execute("""INSERT INTO [CCSBC-DW1].[SurveyMonkey].[dbo].Surveylist (SurveyId, Description, WebSite)
                  SELECT J_open.*
                  FROM dbo.InboundJson j
                  CROSS APPLY OPENJSON(j.[json], '$.data') 
                              WITH (id int,
                                    title varchar(200),
                                    href varchar(200)) j_open;
               """)
conn.commit()
© www.soinside.com 2019 - 2024. All rights reserved.