MySQL 错误:Incorrect datetime value 解决方案
MySQL 错误:Incorrect datetime value 解决方案
当尝试将不正确的日期时间值插入到 MySQL 数据库列中时,您可能会遇到错误 'Incorrect datetime value'。
例如,以下错误信息表明尝试将 '1681609074331' 插入到名为 'optime' 的列中失败,因为该值不符合日期时间格式:
error: code = InvalidArgument desc = Incorrect datetime value: '1681609074331' for column 'optime' at row 1 (errno 1292) (sqlstate 22007) (CallerID: xller9w9ptvm9si08uie): Sql: "insert into nepu(username, `password`, optime) values (:vtg1, :vtg2, :vtg3)", BindVars: {REDACTED}
该错误通常发生在使用 new Date().getTime() 获取当前时间戳并将时间戳作为字符串插入到数据库中时,因为时间戳的格式可能与数据库的日期时间格式不匹配。
解决方案
为了解决这个问题,您可以将 new Date() 对象直接传入 SQL 语句中,这样 MySQL 可以自动识别并处理日期时间值。
以下示例代码展示了如何将 new Date() 对象传入 SQL 语句:
connection.query(
`INSERT INTO nepu (username,password,optime) VALUES (?, ?, ?)`,
[req.query.account, req.query.password, new Date()],
function(err, results) {
if(err) {
console.log(err)
}
console.log(results)
}
)
通过使用 new Date() 对象,您无需进行时间戳转换,可以避免 'Incorrect datetime value' 错误。
原文地址: https://www.cveoy.top/t/topic/nqYe 著作权归作者所有。请勿转载和采集!