phpmyadmin 中的 INSERT 命令运行良好:
INSERT INTO babydb.sales_agro_products (customer_id, product_name, product_class, product_price_kG, amount_ordered, sales_value, Date) VALUES ('Big John', 'Kill Everything', 'product_class', 112.34, 678, 76166.52, STR_TO_DATE('05/08/2024', '%d/%m/%Y'))
现在我想使用 pymysql 在 Python 中执行此操作。没有日期就可以正常工作:
import pymysql.cursors
def insert(cname, pname, pclass, priceKg, kilos, totalprice):
# Connect to the database
connection = pymysql.connect(host='localhost',
user='pedro',
password='letmein',
database='babydb',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
with connection:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO sales_agro_products (customer_id, product_name, product_class, product_price_kG, amount_ordered, sales_value) VALUES (%s, %s, %s, %s, %s, %s)"
cursor.execute(sql, (cname, pname, pclass, priceKg, kilos, totalprice))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM sales_agro_products"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
但这不起作用:
sql = "INSERT INTO sales_agro_products (customer_id, product_name, product_class, product_price_kG, amount_ordered, sales_value, Date) VALUES (%s, %s, %s, %s, %s, %s, STR_TO_DATE(%s, '%d/%m/%Y')"
cursor.execute(sql, (cname, pname, pclass, priceKg, kilos, totalprice, date))
我得到:
类型错误:格式字符串参数不足
我认为这些是造成麻烦的原因:%d/%m/%Y
我应该如何在 pymysql INSERT 命令中正确使用 STR_TO_DATE(%s, '%d/%m/%Y') ?
您刚刚错过了 VALUES 子句的右括号
VALUES (%s, %s, %s, %s, %s, %s, STR_TO_DATE(%s, '%d/%m/%Y')
)"