当前位置:网站首页>Go SQL parsing time Time type

Go SQL parsing time Time type

2022-06-26 04:07:00 Believe in the reason and follow the reason

Code :

package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"time"
)

var db *sqlx.DB // Connect pool objects 

/*  initialization mysql dsn The format is  username:[email protected](ip:port)/database maxOpenConns int // Set the maximum number of connections in the connection pool  maxIdleConns int // Set the maximum number of idle  */


type person struct {
    
	Name string
	Age int32
	Create_time time.Time
}

func main() {
    
	// Connect to database 
	var err error
	db, err = sqlx.Connect("mysql", "root:[email protected](127.0.0.1:3306)/person")
	if err != nil {
    
		fmt.Println("[fail] sqlx.Connect failed,err:",err)
		return
	}

	db.SetMaxOpenConns(1024) // Set the maximum number of connections in the connection pool 
	db.SetMaxIdleConns(512)	// Set the maximum number of idle 

	fmt.Println("[success] Init mysql successfully")

	if db == nil {
    
		panic("db is nil,please init")
	}
	sqlStr := `select * from student where name = ?`
	var s person
	err = db.Get(&s,sqlStr," ask ")
	if err != nil {
    
		fmt.Println("[fail] db.Get() failed,err:",err)
		return
	}
	fmt.Println("[success] getOneStudent successfully,p:",s)

}



sql analysis time Type error :

[success] Init mysql successfully
[fail] db.Get() failed,err: sql: Scan error on column index 2, name "create_time": unsupported Scan, storing driver.Value type []uint8 into type *time.T
ime

solve : In connection sql Pass in the parameter parseTime=true

db, err = sqlx.Connect("mysql", "root:[email protected](127.0.0.1:3306)/person?parseTime=true")

Running results :

[success] Init mysql successfully
[success] getOneStudent successfully,p: {
     ask  0 0001-01-01 00:00:00 +0000 UTC}

When inserted time Default to error :

// Insert 
	sqlStr = `insert into student(name,age,create_time) values(?,?,?)`
	var p person
	_,err = db.Exec(sqlStr, p.Name, p.Age, p.Create_time)
	if err != nil {
    
		fmt.Println("[fail] db.Exec() failed,err:",err)
		return
	}
	fmt.Println("[success] db insert successfully")
[fail] db.Exec() failed,err: Error 1292: Incorrect datetime value: '0000-00-00' for column 'create_time' at row 1

You can format the time and insert it

_,err = db.Exec(sqlStr, p.Name, p.Age, p.Create_time.Format("2006-01-02 15:04:05"))
原网站

版权声明
本文为[Believe in the reason and follow the reason]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180539280393.html