Skip to content

Instantly share code, notes, and snippets.

@atomaths
Last active December 13, 2015 18:18
Show Gist options
  • Save atomaths/4953725 to your computer and use it in GitHub Desktop.
Save atomaths/4953725 to your computer and use it in GitHub Desktop.
Go database/sql and mymysql package usage
package main
import (
"database/sql"
"fmt"
_ "github.com/ziutek/mymysql/godrv"
)
func OpenDB() *sql.DB {
db, err := sql.Open("mymysql", fmt.Sprintf("tcp:%s*%s/%s/%s", DB_HOST, DB_NAME, DB_USER, DB_PASS))
if err != nil {
panic(err)
}
return db
}
func main() {
db := OpenDB()
defer db.Close()
stmt, err := db.Prepare("SELECT title, content FROM memo WHERE id = ?")
defer stmt.Close()
id := 123
rows, err := stmt.Query(id)
defer rows.Close()
if err != nil {
panic(err)
}
if rows.Next() == false {
return
}
var title, content string
rows.Scan(&title)
rows.Scan(&content)
fmt.Printf("%s - %s\n", title, content)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment