Golang将NULL插入sql而不是空字符串 [英] Golang Insert NULL into sql instead of empty string
本文介绍了Golang将NULL插入sql而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用golang将数据插入mysql数据库.在我的值采用空字符串的情况下,我想插入一个空值.如何调整以下内容以插入空值而不是空字符串?谢谢.
I'm trying to insert data into a mysql database using golang. In the case where my value takes on an empty string, I would want to insert a null. How can I adjust the following to insert nulls instead of empty string? Thanks.
_, err := m.Db.Exec(`INSERT INTO
visitor_events
(type,
info,
url_path,
visitor_id,
created_at,
domain)
VALUES
(?, ?, ?, ?, ?, ?)`,
m.SaveEventType(ve), ve.EventInfo, m.SaveURLPath(ve.UrlPath), ve.VisitorId, time.Now().UTC(), ve.Domain)
推荐答案
In my code I have a function that converts a string to sql.NullString
func NewNullString(s string) sql.NullString {
if len(s) == 0 {
return sql.NullString{}
}
return sql.NullString{
String: s,
Valid: true,
}
}
然后,每当我使用 Exec
时,我都会使用 NewNullString
函数将可能为NULL的字符串包装在数据库中.
Then whenever I am using Exec
I wrap my strings that could be NULL in the DB with the NewNullString
function.
db.Exec(`
insert into
users first_name, last_name, email
values (?,?,?)`,
firstName,
lastName,
NewNullString(email),
)
这篇关于Golang将NULL插入sql而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文