我的计划是将日期 (day_of_test) 插入 MySql 数据库,其中数据格式被引用为日期。
我必须将语法保留为您在下面看到的格式。但不幸的是,我尝试将日期专门存储为语法 VALUES(%s...) 中的字符串似乎不起作用。
有人知道调整语法以成功插入 day_of_test 的最简单方法吗?
非常感谢大家
import mysql.connector
mydb = mysql.connector.connect(host="34.xxx.xxx.xxx", user="xxxx", password="xxxxx", database='btc-analysis-db')
c = mydb.cursor()
btc_est = 150.2
sap_close = 100.23
gold_close = 120.2
bonds_close = 210.12
btc_actual = 130.12
day_of_test = "2022-04-20"
c = mydb.cursor()
c.execute(
"INSERT INTO `ML1`(`day_of_test`, `btc_est`, `sap_close`, `bonds_close`, `gold_close`, `btc_actual`) VALUES (%s, %d, %d, %d, %d, %d);" % (
day_of_test, btc_est, sap_close, bonds_close, gold_close, btc_actual))
mydb.commit()
c.execute("select * from ML1")
result = c.fetchall() Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您使用 python 字符串格式,那么您在日期值周围缺少引号,您的语法应该是:
c.execute( "INSERT INTO `ML1`(`day_of_test`, `btc_est`, `sap_close`, `bonds_close`, `gold_close`, `btc_actual`) VALUES ('%s', %d, %d, %d, %d, %d);" % ( day_of_test, btc_est, sap_close, bonds_close, gold_close, btc_actual))但你不应该那样做。你应该使用准备好的语句(以避免 SQL 注入和其他问题),并且你的语法应该是这样的:
c.execute( "INSERT INTO `ML1`(`day_of_test`, `btc_est`, `sap_close`, `bonds_close`, `gold_close`, `btc_actual`) VALUES (%s, %s, %s, %s, %s, %s);", ( day_of_test, btc_est, sap_close, bonds_close, gold_close, btc_actual))