go web开发第4讲- 数据库相关操作(mysql)
操作步骤
- 安装sql驱动,go get github.com/Go-SQL-Driver/MySQL
- 引入sql驱动
- 声明全局变量,var db *sql.DB
- 连接数据库sql.Open("mysql","root:root@tcp(127.0.0.1:3306)/test_new");
- 进行数据的查询 db.Query("select id,title from news")
具体代码如下:
func handleDb(w http.ResponseWriter, r *http.Request) {
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test_new")
if err != nil {
panic(err)
}
rows, err := db.Query("select id,title from news")
if err != nil {
panic(err)
}
var (
id string
title string
)
var news []string
for rows.Next() {
rows.Scan(&id, &title)
news = append(news, title)
}
templates.ExecuteTemplate(w, "db.html", news)
}