Golang connecting to MySQL time zone issues

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The time field using MySQL encountered the following two questions
1. Use Go-sql-driver to connect to the MySQL database, get the time zone default is UTC +0, and the local East Eight is a difference, there will be problems in business processing
2. Get the date in MySQL, which is a string type, that needs to be used in code time. Parse for conversion

Solution:
In a connected DSN, add parseTime=true and loc=Local , here, local can be swapped for a specific time zone(Asia/Shanghai)

Example code:

package mainimport (    "database/sql"    "fmt"    "time"    _ "github.com/go-sql-driver/mysql")func main() {    db, err := sql.Open("mysql",     "bp:123456@tcp(10.13.4.161:3309)/bp_members?parseTime=true&loc=Local")    var myTime time.Time    rows, err := db.Query("SELECT current_timestamp()")    fmt.Println(time.Now())    if rows.Next() {        if err = rows.Scan(&myTime); err != nil {            panic(err)        }    }    fmt.Println(myTime)}
  #运行结果, already consistent 2017-05-27 11:26:32.387955955 +0800 cst2017-05-27 11:26:32 +0800 CST  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.