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

相关推荐
2501_945424804 小时前
构建一个基于命令行的待办事项应用
jvm·数据库·python
内网渗透4 小时前
Komari 部署教程:无数据库、单文件、Docker 一键启动的监控工具
数据库·docker·容器·内网穿透·cpolar·远程办公·komari
未来龙皇小蓝4 小时前
【MySQL-索引调优】08:模糊查询与索引
数据库·mysql·性能优化
项目工程打工马4 小时前
Ubuntu 上 MySQL 详细安装指南
mysql·ubuntu·adb
数据知道4 小时前
《深入掌握MongoDB数据库》 - 专栏介绍和目录
网络·数据库·mongodb
moxiaoran57534 小时前
使用ShardingSphere实现MySQL读写分离(一)
数据库·mysql
CoovallyAIHub4 小时前
BMW GenAI4Q:每57秒下线一辆车,AI如何为每辆车定制专属质检清单
数据库·算法·架构
wang2455981995 小时前
Redis基础——1、Linux下安装Redis(超详细)
linux·数据库·redis
oscar9995 小时前
Memurai:Redis官方认可的Windows原生解决方案
数据库·windows·redis
A10169330715 小时前
redis的启动方式
数据库·redis·bootstrap