[Go] golang连接查询mysql
程序员文章站
2022-07-05 14:54:54
package main import ( "database/sql" _ "github.com/go-sql-driver/mysql" "log" ) func main() { //连接数据库查询 db, err := sql.Open("mysql", "root:xxx@tcp(xxx... ......
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()
}