Go-sql-driver packet implementation MySQL indefinite field query

Source: Internet
Author: User

Go-sql-driver package is a third party Package /http/github.com/go-sql-driver/mysql directly below the code

Package Mainimport ("Database/sql" "Fmt" _ "Github.com/go-sql-driver/mysql") func main () {//Connect database db, err: = SQL. Open ("MySQL", "Root: @tcp (localhost:3306)/go?charset=utf8") if err! = Nil {fmt. PRINTLN ("Connection database Failed", err.) Error ()) Return}defer db. Close ()//queries the database for query, err: = db. Query ("SELECT * from Go_user") if err! = Nil {fmt. PRINTLN ("Query database Failed", err.) Error ()) Return}defer query. Close ()//read out the Queried column field name Cols, _: = Query. Columns ()//values is the value of each column, which gets into byte values: = Make ([][]byte, Len (cols))//query. Scan parameters, because each query comes out of the column is indefinite, with Len (cols) fixed the length of the query when scans: = Make ([]interface{}, Len (cols))//Let each row of data are populated [][]byte inside for I: = Range values {Scans[i] = &values[i]}//last obtained mapresults: = Make (map[int]map[string]string) I: = 0for query. Next () {//loop, let the cursor push down if err: = Query. Scan (Scans ...); Err! = Nil {//query. The indefinite Long value of the scan query is placed in scans[i] = &values[i], i.e. each line is placed in the values of the FMT. PRINTLN (err) Return}row: = Make (map[string]string)/per line of data for k, V: = range values {//each row of data is placed in values, now move it to row key: = Cols [K]row[key] = string (v)}results[i] = row//loading result setThe i++}//query comes out of the array for k, V: = Range Results {FMT. Println (k, v)}db. Close ()//run out close}



Note: The original is http://www.du52.com/text.php?id=562 I made a comment, so easy to understand point

Go-sql-driver packet implementation MySQL indefinite field query

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.