将列表中的元素插入 mysql 数据库时出现类型错误

TypeError when inserting elements from list into mysql database

我正在尝试使用 python、mysql 数据库和 mysqldb 将列表中的每个值插入到数据库中。数据库中此列表中所有元素的类型均为 VARCHAR。

但是我收到这个错误:

类型错误:在字符串格式化期间并非所有参数都已转换

列表理解是为了删除空字符串,为了尝试解决当前的这个问题,我尝试将每个元素转换为字符串,但没有奏效。我也试过在查询函数中将它转换为字符串,但也没有用。

值为 -3.89738e-05

类型(值)是 "type 'str'"

for scan in outer:
    scan = [str(x) for x in scan if x]
    for value in scan:
        print value
        print type(value)
        sql_insert = ('INSERT INTO langmuir_data(currentI)'
                      'VALUES("%s")')
        cursor.execute(sql_insert, str(value))

有人知道我为什么会收到此错误以及如何解决它吗?

当您执行参数化查询时,它希望参数在可迭代对象(我在评论中放入的元组)中传递。当您传递多个参数时,您不会发现任何问题,因为它会将这些参数解压到您提供的占位符中。但是,当您传递单个字符串时,它在 Python 中仍然是可迭代的,因此它会尝试将该字符串逐个字符地插入到您准备好的语句中。

for item in ('abc',):
    print item # prints whole string, for which you provided a placeholder

for item in 'abc':
    print item # prints the individual letters, but you only gave 1 placeholder

因此,您应该使用以下内容:

cursor.execute(sql_insert, (str(value),))