package introduction1
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func ConnMysql() {
connStr := "root:root@tcp(127.0.0.1:3306)/hups_go"
db, err := sql.Open("mysql", connStr)
if err != nil {
fmt.Printf("Connect mysql fail: %s\n", err)
} else { // 连接成功
fmt.Println("Connect to mysql success")
}
defer db.Close()
sqlQuery := "select * from user"
rows, err := db.Query(sqlQuery)
if err != nil {
fmt.Printf("select fail: %s\n", err)
}
// var mapUser map[string]int
// mapUser = make(map[string]int)
var mapUser = make(map[string]int)
for rows.Next() {
var id int
var userName string
rows.Columns()
err := rows.Scan(&id, &userName)
if err != nil {
fmt.Printf("get user info error: %s\n", err)
}
mapUser[userName] = id
}
for k, v := range mapUser {
fmt.Println(k, v)
}
}
Go语言连接Mysql数据库