我的代码:
cursor = cnx.cursor()
xlsx = pd.read_excel('online_retail.xlsx')
for index, row in xlsx.iterrows():
values = [row['Invoice'],
row['StockCode'],
row['Description'],
row['Quantity'],
row['InvoiceDate'],
row['Price'],
row['Customer ID'],
row['Country']]
INSERT_INTO = (f"INSERT INTO online_retail.registers VALUES {values[0]}, "
f"{values[1]}, "
f"{values[2]}, "
f"{values[3]}, "
f"{values[4]}, "
f"{values[5]}, "
f"{values[6]}, "
f"{values[7]}")
cursor.execute(INSERT_INTO)
我的数据库架构:
CREATE TABLE online_retail.registers (
invoice INT NOT NULL,
stock_code VARCHAR(6) NOT NULL,
description TEXT,
quantity INT ,
invoice_date DATETIME(0),
price FLOAT,
customer_ID INT,
country VARCHAR(32),
PRIMARY KEY(invoice)
);
数据示例: 文本数据
错误: mysql.connector.errors.ProgrammingError: 1064 (42000): 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行 '489434, 85048, 15CM CHRISTMAS GLASS BALL 20 LIGHTS, 12, 2009-12-01 07:45:00, 6.9' 附近使用的正确语法
为什么我会收到此错误以及如何继续?
我该如何解决这个问题?
在 SQL 中,
VALUES
子句中的每个数据项集合都需要左括号和右括号。此外,通过省略 INSERT INTO
子句中的列,查询依赖于列的顺序位置,如果添加新列或删除旧列,则可能会引发错误。考虑显式声明列。为了更安全、更快速的处理,请考虑使用 pandas 的 cursor.executemany
和 numpy 的 to_numpy()
来参数化列值列表:
tolist()