![](/img/trans.png)
[英]Getting “Not all parameters were used in the SQL statement” error, when trying to import data to MySQL using python
[英]Why am I getting this Not all parameters were used in the SQL statement error using python?
我有一個帶有一個表的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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.