Golang 中处理 MySQL 的 DATETIME 类型
在 Go 语言中处理 MySQL 的 DATETIME 类型时,通常会使用 time.Time
类型来表示日期和时间。以下是几种常见的处理方式:
1. 使用标准库 database/sql
import (
"database/sql"
"time"
_ "github.com/go-sql-driver/mysql"
)
// 查询 DATETIME
var createdAt time.Time
err := db.QueryRow("SELECT created_at FROM users WHERE id = ?", id).Scan(&createdAt)
if err != nil {
// 处理错误
}
// 插入或更新 DATETIME
_, err = db.Exec("INSERT INTO users (name, created_at) VALUES (?, ?)", name, time.Now())
2. NULL DATETIME 处理
对于可为 NULL 的 DATETIME,可以使用 sql.NullTime
:
var updatedAt sql.NullTime
err := db.QueryRow("SELECT updated_at FROM users WHERE id = ?", id).Scan(&updatedAt)
if err != nil {
// 处理错误
}
if updatedAt.Valid {
fmt.Println("更新时间:", updatedAt.Time)
} else {
fmt.Println("未更新过")
}
3. ORM(如 GORM)中的处理
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string
CreatedAt time.Time // GORM会自动管理创建时间
UpdatedAt time.Time // GORM会自动管理更新时间
}
// AutoMigrate会创建包含DATETIME字段的表
db.AutoMigrate(&User{})
// CRUD操作示例
user := User{Name: "John"}
result := db.Create(&user) // CreatedAt和UpdatedAt会自动设置
var fetchedUser User
db.First(&fetchedUser, user.ID)
4. JSON序列化时的格式化
默认情况下,time.Time
会被序列化为RFC3339格式。如果需要自定义格式:
type CustomUser struct {
Name string `json:"name"`
CreatedAt time.Time `json:"created_at" gorm:"type:datetime"`
}
// MarshalJSON方法自定义格式
func (u *CustomUser) MarshalJSON() ([]byte, error) {
type Alias CustomUser
return json.Marshal(&struct {
*Alias
CreatedAt string `json:"created_at"`
}{
Alias: (*Alias)(u),
CreatedAt: u.CreatedAt.Format("2006-01-02 15:04:05"),
})
}
MySQL与Go的时间类型对应关系
MySQL类型 | Go类型 |
---|---|
DATETIME | time.Time |
TIMESTAMP | time.Time |
DATE | time.Time (时间部分为00:00:00) |
TIME | string / custom type |
注意:在处理不同时区时要特别小心,建议在应用层统一使用UTC时间存储和处理。
内容由零声教学AI助手提供,问题来源于学员提问