【问题标题】:Error when importing csv into MySQL With Python使用 Python 将 csv 导入 MySQL 时出错
【发布时间】:2013-02-24 17:41:35
【问题描述】:

您好,我才刚开始接触 Python,

我已经用一个简单的测试编写了这个 .py 文件,并且运行良好,但是当我只是简单地添加更多 %s 时,它就爆炸了:

错误: File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 159, in execute query = query % db.literal(args) TypeError: not enough arguments for format string

Python 脚本:


import csv
 import MySQLdb

  mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='******',
    db='kestrel_keep')

cursor = mydb.cursor()

csv_data = csv.reader(file('data_csv.log'))

for row in csv_data:

        cursor.execute('INSERT INTO `heating` VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,)',
       row)
#close the connection to the database.
mydb.commit()
cursor.close()
import os


print "Done"

CSV 文件格式:

2013-02-21,21:42:00,-1.0,45.8,27.6,17.3,14.1,22.3,21.1,1,1,2,2
2013-02-21,21:48:00,-1.0,45.8,27.5,17.3,13.9,22.3,20.9,1,1,2,2

有什么想法吗??

谢谢。

【问题讨论】:

  • 在对 cursor.execute 的调用中有 14 个“%s”占位符,但示例 CSV 文件的每一行只有 13 个项目。这可能是一个很好的起点。
  • 是的,当我删除最后一个时出现列数错误???
  • 你的数据库的热表有多少列?您可以通过运行mysql 命令行客户端并执行语句DESC heating 来找到它。
  • 非常感谢亚当,我不敢相信我错过了????简单的东西嘿嘿!!!我想只是需要另一套眼睛!

标签: python mysql csv import


【解决方案1】:

检查检查并再次检查!

我有不同的字段数..

即如果您收到上述错误,通常是因为您的 csv 与 %s 占位符的数量不同。当您的 mysql 表列存在差异时,您将收到列计数错误。

感谢 Adam Mihalcin 帮助指出这一点!

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2016-10-06
    • 2020-01-05
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多