blog_backend_api/db/utils.go

67 lines
1.1 KiB
Go
Raw Normal View History

2019-01-25 09:11:15 +00:00
package db
import (
"database/sql"
2019-03-07 02:36:09 +00:00
"strconv"
"strings"
2019-01-25 09:11:15 +00:00
)
// 根据传入的字段列表生成相符数量的占位符
func GetPlaceholderByFields(fileds string) string {
fileds = strings.Replace(fileds, " ", "", -1)
fileds = strings.Trim(fileds, ",")
count := len(strings.Split(fileds, ","))
ret := make([]string, count)
for i := 0; i < count; i++ {
ret[i] = "?"
}
return strings.Join(ret, ",")
}
// Atoi 转换成整型
func Atoi(s string, d ...int) int {
i, err := strconv.Atoi(s)
if err != nil {
if len(d) > 0 {
return d[0]
} else {
return 0
}
}
return i
}
// Atoi64 转换成整型int64
func Atoi64(s string, d ...int64) int64 {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
if len(d) > 0 {
return d[0]
} else {
return 0
}
}
return i
}
// 返回一个带有Null值的数据库字符串
func NewNullString(s string) sql.NullString {
if len(s) == 0 {
return sql.NullString{}
}
return sql.NullString{
String: s,
2019-03-07 02:36:09 +00:00
Valid: true,
2019-01-25 09:11:15 +00:00
}
}
// 返回一个带有Null值的数据库整形
func NewNullInt64(s int64, isNull bool) sql.NullInt64 {
return sql.NullInt64{
Int64: s,
Valid: !isNull,
}
2019-03-07 02:36:09 +00:00
}