【问题标题】:TypeError: not all arguments converted during string formatting with MySQLTypeError:在使用 MySQL 进行字符串格式化期间并非所有参数都转换了
【发布时间】:2017-11-27 23:10:45
【问题描述】:

我正在编写用于从存档 CSV 插入表“noticias”信息的代码,但它不起作用,当我调试时,此错误显示:

Connected to pydev debugger (build 171.4694.38)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.4\helpers\pydev\pydevd.py", line 1591, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.4\helpers\pydev\pydevd.py", line 1018, in run
pydev_imports.execfile(file, globals, locals)  # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.1.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/SoriyAntony/PycharmProjects/cnnbd/cnnbd", line 11, in <module>
cursor.execute("INSERT INTO noticias(title, link, pubDate) \ VALUES({1},{2},{3})" % tuple(list))
TypeError: not all arguments converted during string formatting

Process finished with exit code 1

这是存档 cnn.csv:

title,link,pubDate

Hundreds of households to be evacuated in wake of London tower fire,http://www.cnn.com/2017/06/23/world/london-fire-safety-evacuations/index.html,"Fri, 23 Jun 2017 20:22:02 GMT"

"Ex-Obama official: Handling of Russia 'is hardest thing to defend,' WaPo reports",http://www.cnn.com/collections/intl-wapo-former-obama-official/,"Fri, 23 Jun 2017 17:47:54 GMT"

"Saudi Arabia, major combatant in Yemen, to tackle spread of cholera",http://www.cnn.com/2017/06/23/middleeast/yemen-saudis-cholera/index.html,"Fri, 23 Jun 2017 18:29:37 GMT"

Violent homophobia festers in Erdogan's shadow,http://www.cnn.com/2017/06/23/europe/turkey-homophobia-violence/index.html,"Fri, 23 Jun 2017 13:11:52 GMT"

Qatar given 10 days to comply with 13 demands from Arab states,http://www.cnn.com/collections/qatar-intl/,"Fri, 23 Jun 2017 11:41:52 GMT"

Al Jazeera: What you need to know,http://www.cnn.com/videos/cnnmoney/2017/06/23/al-jazeera-explainer-mxb-lon-orig.cnnmoney,"Fri, 23 Jun 2017 16:01:18 GMT"

这是代码:

import mysql.connector
import pandas as pd

cnx = mysql.connector.connect(user='root', password='password', host='localhost', database='cnn')
cursor = cnx.cursor()
csv_data = pd.read_csv('cnn.csv')

for row in csv_data.iterrows():
list = row[1].values
#cursor.execute("""INSERT INTO noticias (title, link, pubDate) VALUES('%s', '%s', '%s');""")
cursor.execute("INSERT INTO noticias(title, link, pubDate) VALUES({1},{2},{3})" % tuple(list))

cursor.close()
cnx.close()

我正在测试两行关于 curso.execute 和第一行,调试未检测到错误但未写入表,第二行标记此处解释的错误。 关于这个错误的任何想法,我已经安装了 python 3.6 和 mysql 5.7

这是表格公告:

 mysql> describe noticias;
 +---------+--------------+------+-----+---------+-------+
 | Field   | Type         | Null | Key | Default | Extra |
 +---------+--------------+------+-----+---------+-------+
 | title   | varchar(500) | YES  |     | NULL    |       |
 | link    | varchar(500) | YES  |     | NULL    |       |
 | pubDate | varchar(500) | YES  |     | NULL    |       |
 +---------+--------------+------+-----+---------+-------+
 3 rows in set (0.00 sec)

【问题讨论】:

  • 你能打印变量列表看看你得到了什么

标签: python mysql database csv


【解决方案1】:

使用% (printf-style) string formatting时,占位符不编号而是使用%s占位符:

cursor.execute(
    "INSERT INTO noticias(title, link, pubDate) VALUES(%s, %s, %s)" % tuple(list))

但是,这是错误的做法;这些值不会被正确引用。您想使用 SQL 参数,只需将您的值作为 second 参数传递给cursor.execute()

cursor.execute(
    "INSERT INTO noticias(title, link, pubDate) VALUES(%s, %s, %s)",
    row[1].values)

我删除了名称list;尽量不要用局部变量来掩盖内置类型。

事实上,您可以使用cursor.executemany() 让 MySQL 重复使用一个查询(使用生成器表达式仅提取每一行的数据,跳过索引):

cursor.executemany(
    "INSERT INTO noticias(title, link, pubDate) VALUES(%s, %s, %s)",
    (r[1:] for r in csv_data.itertuples()))

【讨论】:

  • 感谢我现在使用 curso.executemany ,并且代码没有错误,但它没有向数据库中插入任何内容我正在检查我的表 noticias 并且它是空的。
  • @aaguirre:您没有提交交易;添加cnx.commit() 电话。可选:使用context manager to manage the transaction
  • 哦,完成了,我忘了提交,现在代码可以工作了。感谢所有 Martijn
  • 我有一个新问题我现在有这个错误:raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'nan' in 'field list'你能帮帮我吗?
  • @aaguirre 不是真的;没有代码和数据的错误消息并不是真的那么有启发性。听起来你有一个新问题要发布!
猜你喜欢
  • 2018-06-14
  • 1970-01-01
  • 2015-01-21
  • 2021-08-19
  • 2015-03-30
  • 1970-01-01
  • 2022-01-10
相关资源
最近更新 更多