Skip to content

Scan TIME into mysql.NullTime error #849

@Chasiny

Description

@Chasiny

Issue description

hello,I scan TIME into mysql.NullTime. As result, it return error as follow

sql: Scan error on column index 0: invalid time string: 00:00:00

Example code

mysql conn like below

chy:chasiny@tcp(chasiny.com:3306)/test_db?charset=utf8&parseTime=true&loc=Local
findSQL := `select start_time, end_time from discount_merchandise where id = ? and state = 1;`
err := db.QueryRow(findSQL,merchandiseId).Scan(&merchandise.StartTime,&merchandise.EndTime)

start_time and end_time are TIME type in mysql
merchandise.StartTime and merchandise.EndTime are mysql.NullTime type

Error log

sql: Scan error on column index 0: invalid time string: 00:00:00

My experimental method to solve this problem

I modify the function parseDateTime in utils.go

func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
	base := "0000-00-00 00:00:00.0000000"
	switch len(str) {
	case 10, 19, 21, 22, 23, 24, 25, 26: 
		if str == base[:len(str)] {
			return
		}
        t, err = time.Parse(timeFormat[:len(str)], str)
        
    // case 8 in order to parse the TIME type
	case 8:								// up to HH:MM:SS, support TIME type
		if str == base[11:11+len(str)] {
			return
		}
        t, err = time.Parse(timeFormat[11:11+len(str)], str)
    // end modify

	default:
		err = fmt.Errorf("invalid time string: %s", str)
		return
	}

	if err == nil && loc != time.UTC {
		y, mo, d := t.Date()
		h, mi, s := t.Clock()
		t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
	}

	return
}

I wonder is there any better solution to solve this problem? Or this driver support mysql TIME type (include NULL value)?
Thanks you very much!

Configuration

Driver version (or git SHA): d523deb (tag: v1.4.0)

Go version: go version go1.10.3 windows/amd64

Server version: MySQL 5.6.40

Server OS: Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions