我的計劃是將日期(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()
uj5u.com熱心網友回復:
如果您使用的是 python 字串格式化,那么您在日期值周圍缺少引號,您的 sintax 應該是:
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 注入和其他問題),并且您的 sintax 應該是這樣的:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/461638.html
