我正在尝试将 CSV 文件导出到 MySQL 数据库,但我似乎无法找出代码中的错误。我相信它应该有效。
import csv
import MySQLdb
mysql_conn = MySQLdb.connect(host='localhost', user='root', passwd='******', db='accounting')
mysql_cursor = mysql_conn.cursor()
f = open('C:/Users/Pops/Desktop/List of Payees.csv')
csv_f = csv.reader(f)
for row in csv_f:
mysql_cursor.execute("""INSERT INTO list_of_payees (list_of_payees) VALUES (%s)""", (row[0]))
mysql_conn.commit()
mysql_cursor.close()
错误代码:
Traceback (most recent call last):
File "C:\Users\Pops\Desktop\Martin\Programming\Python\venv\lib\site-packages\MySQLdb\cursors.py", line 238, in execute
query = query % args
TypeError: not all arguments converted during string formatting
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Pops/Desktop/Martin/Programming/Python/ExcelToMySQL.py", line 11, in <module>
mysql_cursor.execute("""INSERT INTO list_of_payees (list_of_payees) VALUES (%s)""", (row[0]))
File "C:\Users\Pops\Desktop\Martin\Programming\Python\venv\lib\site-packages\MySQLdb\cursors.py", line 240, in execute
self.errorhandler(self, ProgrammingError, str(m))
File "C:\Users\Pops\Desktop\Martin\Programming\Python\venv\lib\site-packages\MySQLdb\connections.py", line 52, in defaulterrorhandler
raise errorclass(errorvalue)
_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting
Process finished with exit code 1
最佳答案
LOAD DATA INFILE是将 csv 文件上传到 MYSQL 表的一种更快更好的方法,读取 CSV 并插入到 MYSQL 表中是一个缓慢且耗时的过程。使用 MYSQLdb 从 python 执行此命令。
示例查询:
LOAD DATA INFILE '/path_of_csv_file/sampledata.csv'
INTO TABLE expenses
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n' -- or \r\n
(column1, column2, column3, column4, column5)
关于python - 尝试导入数据到MySQL时出现 "TypeError: not all arguments covered during string formatting"是什么原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283225/