python - 为什么我会收到此错误:Not allparameters wereused in the SQL statements using python?

标签 python mysql csv

我有一个 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/

相关文章:

mysql - 如果存在具有此列的 View ,如何防止表列更改?

python - 如何将csv文件中的数据插入sqlite db?

python - Mxnet 数据类型是 float64,但一直说它是 float32

使用 iso-8859-1 编码的主题进行 Python IMAP 搜索

javascript - 如何在ajax中放置条件警报框

c# - 在 C# 中写入 CSV 时,数字字段丢失前导零

csv - 如何在 VB6 中根据匹配值合并两个 CSV 文件

python - 如何将字典转换为 Pandas DataFrame,并将特定键作为 Python 中的列名称?

python - GCS - 具有目录结构的 Python 下载 blob

MySQL 指定天数的平均温度