在SQL中,中的每个数据项集合
VALUES
子句需要左括号和右括号。此外,通过省略中的列
INSERT INTO
子句中,查询依赖于列的顺序位置,如果添加新列或删除旧列,这些列可能会引发错误。请考虑显式声明列。为了更安全、更快地进行处理,请考虑使用参数化
cursor.executemany
使用熊猫的
to_numpy()
和numpy的
tolist()
对于列值列表的列表:
retail_df = pd.read_excel('online_retail.xlsx')
cursor = cnx.cursor()
sql = (
"INSERT INTO online_retail.registers ("
" invoice, stock_code, description, quantity,"
" invoice_date, price, customer_ID, country) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
)
values = (
retail_df.reindex(
[
'Invoice', 'StockCode', 'Description', 'Quantity',
'InvoiceDate', 'Price', 'Customer ID', 'Country'
],
axis = "columns"
).to_numpy().tolist()
)
cursor.executemany(sql, values)