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

标签 python sql-server python-3.x csv pyodbc

所以我正在尝试将 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/

相关文章:

string - Python中的文件读取问题

python - 帮助在元组匹配 Python 函数中使用 *args

python - 如何释放对象中的 Python 列表?

python - 添加到ManyToMany Django;没有这样的列错误

GROUP BY 子句中的 SQL Geography 数据类型列

python - 字典键*值到python中的列表

python - 如何使用 NaT 值正确处理整个 DataFrame 中的日期时间比较?

python - 使用 python 库发送 xmpp 消息

c# - Entity Framework 可以在 SQL 中生成 UPDATE ... WHERE 语句吗?

sql-server - CLR 程序集表示找不到数据库中已存在的引用程序集