Heim  >  Fragen und Antworten  >  Hauptteil

Formatieren von Datumswerten für MySql

Mein Plan besteht darin, ein Datum (day_of_test) in eine MySql-Datenbank einzufügen, in der das Datenformat als Datum referenziert wird.

Ich musste die Syntax in dem Format beibehalten, das Sie unten sehen. Aber leider scheinen meine Versuche, das Datum gezielt als String in der Syntax VALUES(%s...) zu speichern, nicht zu funktionieren.

Kennt jemand den einfachsten Weg, die Syntax anzupassen, um day_of_test erfolgreich einzufügen?

Vielen Dank an alle

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 Tage vor292

Antworte allen(1)Ich werde antworten

  • 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))

    Antwort
    0
  • StornierenAntwort