1. Mysql connection function
// Introduce two libraries
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" // SQL depends on this mysql extension
)
// Create a mysql connection
func NewMysqlConn(db *sql.DB, err error) {
db, err = sql.Open("mysql"."Root: 123456 @ TCP (127.0.0.1:3306)/test? charset=utf8")
return
}
Copy the code
Mysql > select * from ‘SQL’ where ‘Rows’ =’ map ‘;
func GetResultRow(rows *sql.Rows) map[string]string{
columns, _ := rows.Columns() / / to get listed
scanArgs := make([]interface{}, len(columns)) // Populate the data
values := make([]interface{}, len(columns)) // Store data values
// Store a pointer to values in scanArgs
for i := range values {
scanArgs[i] = &values[i]
}
// The map used to hold the entire query result
record := make(map[string]string)
for rows.Next() {
// Scan method assignment
rows.Scan(scanArgs...)
// There is a value in values because of pointer binding, traversal assigns value to record
for i, v := range values {
ifv ! =nil {
record[columns[i]] = string(v.([]byte)) // An assertion is required, and then the string method is converted to a string}}}return record
}
Copy the code
SQL.Rows = map[int]map[string]string
func GetResultRows(rows *sql.Rows) map[int]map[string]string {
// Return all columns
columns, _ := rows.Columns()
// Identifies the values of all columns in a row, denoted by []byte
vals := make([] []byte.len(columns))
// This marks a row of fill data
scans := make([]interface{}, len(columns))
// here scans refer to vals and insert data into []byte
for k, _ := range vals {
scan[k] = &val[k]
}
i := 0
result := make(map[int]map[string]string)
for row.Next() {
// Populate the data
rows.scan(scans...)
// Data per row
row := make(map[string]string)
// Assign data from VALS to row
for k, v := range vals {
key := columns[k]
// Convert []byte data to string
row[key] = string(v)
}
// Put the result set
result[i] = row
i++
}
return result
}
Copy the code