当先锋百科网

首页 1 2 3 4 5 6 7

package main

import (

"database/sql"

_ "github.com/go-sql-driver/mysql"

"log"

)

func main() {

//连接数据库查询

db, err := sql.Open("mysql", "root:xxx@tcp(xxx:3306)/my_test")

if err != nil {

log.Fatal(err.Error())

}

//最终关闭数据库

defer db.Close()

mSql := "select * from user"

rows, err := db.Query(mSql)

if err != nil {

log.Fatal(err.Error())

}

//获取列名

columns, _ := rows.Columns()

//定义一个切片,长度是字段的个数,切片里面的元素类型是sql.RawBytes

values := make([]sql.RawBytes, len(columns))

//定义一个切片,元素类型是interface{} 接口

scanArgs := make([]interface{}, len(values))

for i := range values {

//把sql.RawBytes类型的地址存进去了

scanArgs[i] = &values[i]

}

//获取字段值

var result []map[string]string

for rows.Next() {

res := make(map[string]string)

rows.Scan(scanArgs...)

for i, col := range values {

res[columns[i]] = string(col)

}

result = append(result, res)

}

//遍历结果

for _, r := range result {

for k, v := range r {

log.Printf("%s==%s", k, v)

}

}

rows.Close()

}

7dc74a4beed421f517df8bcf145a13f9.png