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
- MySQL does not seem to support date and time data types and must use the datetime type.
- MySQL does not seem to support datetime value ' 0000-00-00 00:00:00 '.
Resources
- https://github.com/go-sql-driver/mysql/
Revision history
- The document was created December 31, 2016.
- May 22, 2017 adds a datetime type conversion problem.
- Changed to RST format on June 17, 2017.