繁体   English   中英

MySql 的日期值格式

[英]Date Values format 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()

如果您使用的是 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 注入和其他问题),你的 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM