[Go] golang连接查询mysql
程序员文章站
2022-04-09 18:00:42
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()
}
上一篇: HTML5知识点汇总(1)
下一篇: vue v-for动画bug