【问题标题】:Select data from JSON output for insert statement in Python从 JSON 输出中为 Python 中的插入语句选择数据
【发布时间】:2020-07-30 16:25:37
【问题描述】:

假设我有一个这样的 JSON:

[
 {
  "randomcol" : "randomvarchar"
 }
]

它是这样生成的:

cursor_orcl.execute("""
                    Select * from test_t where 
            """)

rows = cursor_orcl.fetchall()
columns = [desc[0] for desc in cursor_orcl.description]
result = []

for row in rows:
    row = dict(zip(columns, row))
    result.append(row) 

我需要由此在 Python 中生成插入 SQL 语句。我想出了以下几点:

...
cursor_insert = cnxn.cursor()
cursor_insert.arraysize= 50000
sql = (
    "INSERT INTO dbo.test_t (randomcol) " + " VALUES("
    "SELECT randomcol" +
    "FROM OPENJSON(?))"
      )

cursor_insert.execute(sql)   
cursor_insert.close ()
cnxn.commit ()

但是它给了我这个错误:'pyodbc.Error: ('07002'. '[07002]' [Microsoft][ODBC Driver 17 for SQL Server]COUNT 字段不正确或语法错误 (0) ( SQLExecDirectW)')'

可能出了什么问题?这只是只有 1 行/列的测试表,我不明白为什么它不起作用。

【问题讨论】:

    标签: python sql json oracle


    【解决方案1】:

    您可以将 JSON 字符串作为字典加载到 Python。

    import json
    yourdict = json.loads({"randomcol":"randomstring"})
    

    之后,您可以像使用任何普通的 python 字典一样使用它。

    【讨论】:

      【解决方案2】:

      在 Oracle 中,您使用的语法是无效的;删除 values 关键字。

      insert into test_t (randomcol) values (select randomcol from openjson)
                                     ------
                                     remove it!
      

      括号也可以删除,所以 - 最后 - 你会得到

      insert into test_t (randomcol) select randomcol from openjson
      

      【讨论】:

      • 它给了我“无效的对象名称'openjson'”。我正在尝试插入 SQL Server (v18.4)。我发现这可能是由于兼容性不足,在我的情况下它设置为 150,所以这应该不是问题吗?好郁闷
      • “无效的对象名称”看起来名为 openjson 的表不存在。您正在从中选择,所以 - 检查它是否存在。注意字母大小写(如果重要)。
      • 我添加了生成 JSON 的方式,在我的情况下,我需要从包含 JSON 格式数据的“结果”中获取值。抱歉,我是新手,所以对我来说有点困难。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多