mysql中date/datetime类型自动转go的时间类型time.Time

在DSN中需要加入parseTime=true&&loc=Local,或
charset=utf8mb4&loc=Asia%2FShanghai&parseTime=true

go 复制代码
package main_test

import (
	"database/sql"
	"fmt"
	"testing"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func TestMysqlDatetime(t *testing.T) {

	type Student struct {
		CreateAt time.Time
	}

	db, _ := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test?parseTime=true&&loc=Local")
	rows, _ := db.Query("SELECT create_at FROM `student`")
	defer rows.Close()
	var student Student
	for rows.Next() {
		err := rows.Scan(&student.CreateAt)
		if err != nil {
			fmt.Printf("scan failed, err:%v\n", err)
			return
		}
		fmt.Println("student.CreateAt:", student.CreateAt.Format("2006-01-02 15:04:05"))
	}
}

参考

https://github.com/go-sql-driver/mysql#timetime-support

相关推荐
唐青枫9 分钟前
MySQL JSON 实战详解:从存储、查询、更新到 JSON_TABLE 与索引
sql·mysql
吃糖的小孩21 分钟前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
小满8781 小时前
5.Mysql事务隔离级别与锁机制
mysql
笃行35018 小时前
金仓数据库数据安全双防线:静态存储加密与传输加密实战
数据库
笃行35018 小时前
金仓数据库物理备份实战:sys_rman 全流程演练与误覆盖抢救
数据库
笃行35018 小时前
金仓数据库逻辑备份实战:从全库导出到 Schema 替换的完整闭环
数据库
元Y亨H19 小时前
技术笔记:MySQL 字符集排序规则与大小写敏感性问题解决方案
mysql
SelectDB2 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
这个DBA有点耶2 天前
GROUP BY优化全解:如何写出既不丢数据又飞快的分组查询
数据库·mysql·架构