Golang MySQL Query returns an indeterminate field

Source: Internet
Author: User
Tags mysql query mysql connect

Golang MySQL Query returns an indeterminate field implemented as follows:
First, the slice of the query field is obtained by func (Rs *rows) Columns ([]string, error), then the slice is constructed, the value of each scan is put in, and finally the map slice of the query result is returned.
Package Main

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

Func Main () {
Conn, err: = SQL. Open ("MySQL", "root:psw@tcp (localhost:3306)/test?charset=utf8")
If Err!= nil {
Fmt. Println ("MySQL Connect error")
Return
}

Defer Conn. Close ()
Rows, err: = conn. Query ("SELECT * from User")
If Err!= nil {
Fmt. PRINTLN ("MySQL query error", err.) Error ())
}
Defer rows. Close ()
Columns, err: = rows. Columns ()

Values: = Make ([]sql. Rawbytes, Len (columns))
Scans: = Make ([]interface{}, Len (columns))

For I: = range values {
Scans[i] = &values[i]
}

var result []map[string]string
For rows. Next () {
_ = rows. Scan (Scans ...)
Each: = Make (map[string]string)

For I, col: = Range Values {
Each[columns[i]] = string (col)
}

result = Append (result, each)

}

Fmt. PRINTLN (Result)
}

The same can be done with the same query single:
Func Main () {
Conn, err: = SQL. Open ("MySQL", "root:psw@tcp (localhost:3306)/test?charset=utf8")
If Err!= nil {
Fmt. Println ("MySQL connect error", err. Error ())
Return
}

Defer Conn. Close ()

Columns: = []string{"id", "name"}
ID: = 1
sql: = Fmt. Sprintf ("Select%s from user where id=%d", strings.) Join (Columns, ","), id)
Row: = conn. Queryrow (SQL)

Values: = Make ([][]byte, Len (columns))
Scans: = Make ([]interface{}, Len (columns))

For I: = range values {
Scans[i] = &values[i]
}

If err: = row. Scan (Scans ...); Err!= Nil {
Fmt. PRINTLN ("Scan error", Err. Error ())
Return
}

var result = make (map[string]string)
For key, Val: = range Values {
Result[columns[key]] = string (val)
}

Fmt. PRINTLN (Result)
}

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.