我有一个 mysql 数据库,其中有一个表,我正在尝试使用 python 从 CSV 导入该表。
我收到的错误是:
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
但是我的表中只有 1 个字段,所以我只使用 1 个参数。
这是 MySQL 中的表:
desc billing_info;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| InvoiceId | int(11) | NO | | NULL | |
+-----------+---------+------+-----+---------+-------+
这是我的代码:
import mysql.connector
import csv
source_dir = 'source_files/aws_bills/'
source_file = 'test_data.csv'
source = source_dir + source_file
mydb = mysql.connector.connect(user='xxxx', password='xxxx',
host='xxxx',
database='aws_bill')
cursor = mydb.cursor()
csv_data = csv.reader(source)
sql = "INSERT INTO billing_info (InvoiceId) VALUES (%i)"
for row in csv_data:
cursor.execute(sql, row)
#close the connection to the database.
mydb.commit()
cursor.close()
最佳答案
您的 row
变量中有多个值,也许您的意思是:
for row in csv_data:
cursor.execute(sql, (row[0],)) # a one-tuple with the first element in the row..
此外,mysql 连接器通常希望您对任何类型的参数使用 %s
,即:
sql = "INSERT INTO billing_info (InvoiceId) VALUES (%s)"
更新:您的第二个问题是您尚未打开该文件,即:
import os
import mysql.connector
import csv
# source_dir = 'source_files/aws_bills/'
# source_file = 'test_data.csv'
# source = source_dir + source_file
source = os.path.join('source_files', 'aws_bills', 'test_data.csv')
sql = "INSERT INTO billing_info (InvoiceId) VALUES (%s)"
mydb = mysql.connector.connect(user='xxxx', password='xxxx', host='xxxx', database='aws_bill')
cursor = mydb.cursor()
try:
with open(source, 'rb') as fp:
for row in csv.reader(fp):
cursor.execute(sql, (row[0],))
cursor.close()
mydb.commit()
except:
mydb.rollback()
finally:
mydb.close()
关于python - 为什么我会收到此错误:Not allparameters wereused in the SQL statements using python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885591/