go web开发第四讲-数据库操作

go 数据库操作(mysql)

  1. 安装sql驱动,go get github.com/Go-SQL-Driver/MySQL
  2. 引入sql驱动
  3. 声明全局变量,var db *sql.DB
  4. 连接数据库sql.Open(“mysql”,“root:root@tcp(127.0.0.1:3306)/test_new”);
  5. 进行数据的查询 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)
}
posted @ 2020-02-28 20:12  梦回丶故里  阅读(135)  评论(0编辑  收藏  举报