格式化 MySql 的日期值
P粉627136450
P粉627136450 2024-02-26 20:50:13
0
1
282

我的计划是将日期 (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粉627136450
P粉627136450

全部回复(1)
P粉958986070

如果您使用 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))
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!