Ways to access MySQL using go

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

Ways to access MySQL using go

Install MySQL Driver

Go get Github.com/go-sql-driver/mysql

Import MySQL Package

Import (    "Database/sql"    _ "Github.com/go-sql-driver/mysql")

Connecting to a database

DB, err: = SQL. Open ("MySQL", "user:password@tcp (127.0.0.1:3306)/dbname") if err! = Nil {    Panic (err. Error ())}defer db. Close () Err = db. Ping () if err! = Nil {    panic (err). Error ())}

Inquire

Age: = 27rows, err: = db. Query ("Select name from the Users WHERE age=?", age) if err! = Nil {    log. Fatalln (Err)}defer rows. Close () for rows. Next () {    var name string    If err: = rows. Scan (&name); Err! = Nil {        log. Fatalln (Err)    }    fmt. Printf ("%s is%d\n", name, age)}if err: = rows. ERR (); Err! = Nil {    log. Fatalln (ERR)}

Problem

DateTime Conversion Issues

Error reporting when executing Rows.scan ()

Sql:scan error on column index 1:unsupported Scan, storing driver. Value type []uint8 into type *time. Time

The reason is that SQL is called. Open () did not set Parsetime to true. You can fix the problem by joining Parsetime:

DB, err: = SQL. Open ("MySQL", "user:password@tcp (127.0.0.1:3306)/dbname?parsetime=true")

Date, time, DateTime, and other data types

    1. MySQL does not seem to support date and time data types and must use the datetime type.
    2. MySQL does not seem to support datetime value ' 0000-00-00 00:00:00 '.

Resources

    1. https://github.com/go-sql-driver/mysql/

Revision history

    1. The document was created December 31, 2016.
    2. May 22, 2017 adds a datetime type conversion problem.
    3. Changed to RST format on June 17, 2017.
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.