英文:
INSERT datetime using now() with Go
问题
我已经参考了上面的帖子。但是在执行INSERT语句时,遇到了一个字段为datetime的问题。我尝试使用"NOW()",但是当我检查mysql数据库时,看到的是0000-00-00 00:00:00。有人知道我可以使用什么值来正确插入datetime吗?
另外,我知道可以使用Go的time包构造datetime,但我不想使用运行Go的机器的时间戳。我想要运行mysql的机器的datetime。所以我使用了"NOW()"。
stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
checkErr(err)
res, err := stmt.Exec("reckhou", "IT", "NOW()")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
英文:
https://stackoverflow.com/questions/16054317/using-sql-database-driver
I've been referencing the post above. But having troubling doing an INSERT statement where one of my fields are for datetime. I tried doing "NOW()" but when I check the mysql db, i am seeing 0000-00-00 00:00:00. Anyone know what I can use as the value to properly have it insert the datetime?
Also- I know I can construct datetime using go's time package, but I do not wish to use the timestamp of the machine running Go. I want the datetime of the machine running mysql. Hency, why I used "NOW()".
stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
checkErr(err)
res, err := stmt.Exec("reckhou", "IT", "NOW()")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Println(id)
答案1
得分: 16
NOW()
需要作为SQL文本的一部分,而不是绑定值。
INSERT INTO userinfo (username, departname, created) VALUES (?, ?, NOW())
你的代码中,MySQL将"NOW()"
视为字面字符串,就像是任意的字符串'foo'
一样。MySQL将该字符串值转换为DATETIME(MySQL期望的格式接近'YYYY-MM-DD HH:MM:SS'
),但无法将其转换为有效的日期。我们预期会得到一个NULL值或者一个特殊的“零日期”,就像你所看到的一样。
英文:
The NOW()
needs to be part of the SQL text, it's not a bind value.
INSERT userinfo SET username=?,departname=?,created=NOW()
The way you have it coded, MySQL is seeing "NOW()"
as a literal string, as if it were any old string like 'foo'
. MySQL is casting that string value to a DATETIME (MySQL is expecting a format close to 'YYYY-MM-DD HH:MM:SS'
, and it's failing to cast that to a valid date. We'd expect either a NULL or a special "zero-date" like you are seeing.
答案2
得分: 14
以下是翻译好的内容:
var datetime = time.Now()
dt := datetime.Format(time.RFC3339)
_, err = DatabaseHandle.Exec("INSERT into userinfo(id, date) VALUES (?,?)", 0, dt)
请注意,这将设置运行Go代码的服务器的当前时间,这可能与MySQL服务器的时间不同(可能不在同一时区等)。
英文:
var datetime = time.Now()
dt := datetime.Format(time.RFC3339)
_, err = DatabaseHandle.Exec("INSERT into userinfo(id, date) VALUES (?,?)", 0, dt)
Beware that this will set the current time of the server running the go code, which might be different from the MySQL Server (might not be the same timezone, etc.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论