首頁  >  問答  >  主體

Formatting Date Values for MySql

我的計劃是將日期 (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()

#
P粉627136450P粉627136450235 天前291

全部回覆(1)我來回復

  • P粉958986070

    P粉9589860702024-02-27 11:12:02

    如果您使用 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))

    回覆
    0
  • 取消回覆