gpt4 book ai didi

python - 类型错误 : object of type 'map' has no len() when trying to insert a CSV into an SQL Server database in Python 3

转载 作者:行者123 更新时间:2023-12-01 06:46:54 24 4
gpt4 key购买 nike

所以我正在尝试将 CSV 文件导入 SQL Server,

示例 csv 文件

STUFF,NAME,A DATE,A TIME,ANOTHER DATE,ANOTHER TIME,A NUMBER Bananas
John Smith,2019-11-20,17:00,2019-11-20,20:00,3 Apples,Jane Doe,2019-11-07,17:00,2019-11-07,23:00,6

这是我尝试执行的方法(基于 this ):

import csv  
import pyodbc

thecsv = 'iamacsvfile.csv'

print('connecting')
drivr = "SQL Server"
servr = "1.2.3.4"
db = "testdata"
username = "user"
password = "thepassword"
my_cnxn = pyodbc.connect('DRIVER={};SERVER={};DATABASE={};UID={};PWD={}'.format(drivr,servr,db,username,password))

my_cursor = my_cnxn.cursor()

def insert_records(table, thecsv, my_cursor, my_cnxn):

with open(thecsv) as csvfile:
csvFile = csv.reader(csvfile, delimiter=',')
header = next(csvFile)
headers = map((lambda x: x.strip()), header)
insert = 'INSERT INTO {} ('.format(table) + ', '.join(headers) + ') VALUES ({})' .format(', '.join(len(headers) * '?'))
for row in csvFile:
values = map((lambda x: x.strip()), row)
my_cursor.execute(insert, values)
my_cnxn.commit()


table = 'dbo.iamthetable'
mycsv = thecsv
insert_records(table, mycsv, my_cursor, my_cnxn)
my_cursor.close()

错误消息:

insert = 'INSERT INTO {} ('.format(table) + ', '.join(headers) + ') VALUES ({})' .format(', '.join(len(headers) * '?'))
TypeError: object of type 'map' has no len()

我见过此类错误的一些类似示例(例如 here ),但我不确定这些解决方案如何应用于此特定用例。有人可以帮忙吗?

(顺便说一句,如果整个代码块很糟糕,我愿意采用完全不同的方法来完成相同的任务,但还没有找到任何有效的方法)

最佳答案

您的两个问题都是由现代版本的 Python(即 Python_3)map() 引起的。返回一个映射对象,它是一个可迭代对象,而不是一个列表。因此,

import csv

with open('C:/Users/Gord/Desktop/foo.csv', 'r') as csvfile:
csvFile = csv.reader(csvfile, delimiter=',')
header = next(csvFile)
print(type(header)) # <class 'list'>
print(len(header)) # 3
headers_map = map((lambda x: x.strip()), header)
print(type(headers_map)) # <class 'map'>
try:
print(len(headers_map))
except TypeError as e:
print(str(e)) # object of type 'map' has no len()
headers_list = list(headers_map)
print(len(headers_list)) # 3

同样,如果你做类似的事情

values = map((lambda x: x.strip()), row)
my_cursor.execute(insert, values)

并得到类似的错误

pyodbc.ProgrammingError: ('The SQL contains 7 parameter markers, but 1 parameters were supplied', 'HY000')

那是因为values是单<class 'map'>对象,其中 pyodbc 期望 list , tuple ,或Row 。因此,定义values作为

values = list(map((lambda x: x.strip()), row))

关于python - 类型错误 : object of type 'map' has no len() when trying to insert a CSV into an SQL Server database in Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59185633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com