ホームページ  >  に質問  >  本文

Formatting Date Values for MySql

私の計画は、データ形式が日付として参照される MySql データベースに日付 (day_of_test) を挿入することです。

構文を以下に示す形式に保つ必要がありました。しかし、残念ながら、日付を構文 VALUES(%s...) の文字列として具体的に保存しようとした試みは機能しないようです。

day_of_test を正常に挿入するために構文を調整する最も簡単な方法を知っている人はいますか?

###皆さん、ありがとうございました###

import mysql.connector mydb = mysql.connector.connect(ホスト = "34.xxx.xxx.xxx", ユーザー = "xxxx", パスワード = "xxxxx", データベース = 'btc-analysis-db') c = mydb.cursor() btc_est = 150.2 sap_close = 100.23 ゴールドクローズ = 120.2 結合終値 = 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("ML1 から * を選択") 結果 = c.fetchall()

P粉627136450P粉627136450235日前290

全員に返信(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
  • キャンセル返事