go连接mysql
package mainimport (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)func main() {
db, err := sql.Open("mysql", "root:***@tcp(127.0.0.1:3200)/server_conf?charset=utf8")
if err != nil {
fmt.Printf("connect mysql failed! [%s]", err)
return
} else {
fmt.Println("connect mysql ok!")
}rows, err := db.Query("SELECT d_id, d_dname FROM domain")
if err != nil {
fmt.Printf("select failed! [%s]", err)
return
}var mapDomain map[string]int
mapDomain = make(map[string]int)
for rows.Next() {
var d_id int
var d_dname stringrows.Columns()
err = rows.Scan(&d_id, &d_dname)
if err != nil {
fmt.Printf("Get domain info failed! [%s]", err)
}mapDomain[d_dname] = d_id
}// 遍历所有的KEY
for k, v := range mapDomain {
fmt.Println(k, v)
}// 查找指定KEY
if v, ok := mapDomain["www.test2.com"];
ok {
fmt.Println(v)
} else {
fmt.Println("Key Not Found")
}
}
【go连接mysql】输出:
connect mysql ok!
推荐阅读
- 【golang】leetcode中级-字母异位词分组&无重复字符的最长子串
- 彻底理解Golang Map
- kratos线上开源年会它来啦~
- 深入浅出 Golang 资源嵌入方案(go-bindata篇)
- 深入浅出 Golang 资源嵌入方案(前篇)
- golang 经典案例总结
- Go实战 | 基于有向无环图的并发执行流的实现
- Golang 数组和切片
- Go JSON编码与解码()
- golang map基础知识