【问题标题】:Confused about python data types to insert into database对插入数据库的 python 数据类型感到困惑
【发布时间】:2021-07-11 08:11:51
【问题描述】:

我正在尝试将此值插入到 SQL Server 表中,但我不确定这应该是列表还是字典。

对于某些上下文,我使用 shareplum 和类似这样的代码从 Sharepoint 列表中提取数据

import json
import pandas
import pyodbc 
from shareplum import Site
from shareplum import Office365

authcookie = Office365('https://company.sharepoint.com', username='username', password='password').GetCookies()
site = Site('https://company.sharepoint.com/sites/sharepoint/', authcookie=authcookie)
sp_list = site.List('Test')
data = sp_list.GetListItems('All Items')

cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=Server;"
                      "Database=db;"
                      "Trusted_Connection=yes;")

cursor = cnxn.cursor()
insert_query = "INSERT INTO SharepointTest(No,Name) VALUES (%(No)s,%(Name)s)"
cursor.executemany(insert_query,data)
cnxn.commit

这是我使用 print(data) 时的结果

[
    { 'No': '1', 'Name': 'Qwe' }, 
    { 'No': '2', 'Name': 'Asd' }, 
    { 'No': '3', 'Name': 'Zxc' }, 
    { 'No': '10', 'Name': 'jkl' }
]

如果我尝试执行该代码将显示此消息

TypeError: ('Params must be in a list, tuple, or Row', 'HY000')

我应该在代码中修复什么?

【问题讨论】:

  • 看看executemany()方法
  • @gvee 之前试过,结果一样
  • 要使用executemany,数据应该是一个元组列表,你目前有一个字典列表。尝试用 list(data.items()) 替换数据。
  • @norie 它给了我这个结果> AttributeError: 'list' object has no attribute 'items'
  • 抱歉,您确实需要一个元组列表,但这不是获取它的正确方法 - 您需要一个循环或列表理解。

标签: python sql-server pandas pyodbc shareplum


【解决方案1】:

将您的字典列表转换为字典值的列表或元组。

我在下面使用列表推导来遍历列表并使用values() 方法从字典中提取值

insert_query = "INSERT INTO SharepointTest(No,Name) VALUES (?, ?)" #change your sql statement to include parameter markers 
cursor.executemany(insert_query, [tuple(d.values()) for d in data])
cnxn.commit() #finally commit your changes

【讨论】:

  • 它给了我pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 2 parameters were supplied', 'HY000') 我想知道它来自我的SQL 表CREATE TABLE SharepointTest (No INT, Name VARCHAR(5))
  • 我看到那个叫做参数标记,我试过了,没有更多的错误信息,但由于某种原因,我可以通过 select * from table 打印出来,但数据没有插入到我的SQL 服务器表。你知道它为什么会这样吗?
  • 您必须提交更改。 cnxn.commit()
  • 谢谢!显然我错过了提交中的括号
猜你喜欢
  • 1970-01-01
  • 2013-08-20
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 2016-09-04
  • 1970-01-01
  • 2012-04-24
相关资源
最近更新 更多