Skip to content

Instantly share code, notes, and snippets.

@komagata
Created July 28, 2016 09:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komagata/9818eba1c32b59b48215bd4c5b24e6d6 to your computer and use it in GitHub Desktop.
Save komagata/9818eba1c32b59b48215bd4c5b24e6d6 to your computer and use it in GitHub Desktop.
毎回MySQLにアクセスするアプリ。
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"html/template"
"net/http"
)
func viewHandler(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("index.html")
if err != nil {
panic(err)
}
//db, err := sql.Open("mysql", "root@tcp(localhost:3306)/sbtest")
db, err := sql.Open("mysql", "root@/sbtest")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query("SELECT id, pad FROM sbtest WHERE id = 100000")
defer rows.Close()
if err != nil {
panic(err.Error())
}
var id int
var pad string
for rows.Next() {
if err := rows.Scan(&id, &pad); err != nil {
panic(err.Error())
}
}
err = tmpl.Execute(w, struct {
Pad string
}{
Pad: pad,
})
if err != nil {
panic(err)
}
}
func main() {
http.HandleFunc("/", viewHandler)
http.ListenAndServe(":8081", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment