使用go-sql-driver操作myql数据库
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "fmt" ) func main() { //连接数据库,获得连接句柄 db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/huifang5?charset=utf8") if err != nil { panic(err.Error()) } defer db.Close() //执行sql语句返回多行的结果集 result, err := db.Query("select * from hf_test where keshiid=?", 0) if err != nil { panic(err.Error()) } defer result.Close() //Scan需要的容器 keys, _ := result.Columns() //字段名 values := make([][]byte, len(keys)) //字段值 scans := make([]interface{}, len(keys)) //Scan时的容器 for i := range scans { scans[i] = &values[i] //对容器的处理,以便能在Scan之后收集到每个字段值 } //循环取出每一行的数据 var datas []map[string]string for result.Next() { result.Scan(scans...) data := make(map[string]string) for k, v := range values { key := keys[k] data[key] = string(v) } datas = append(datas, data) } fmt.Println(datas) }
有疑问加站长微信联系(非本文作者)