package main
import {
"database/sql"
"log"
_ "github.com/go-sql-driver/mysql"
}
func dbConn() *sql.DB {
db, err := sql.Open("mysql",
"myusername:mypassword@tcp(127.0.0.1:3306)/MYDB")
if err != nil {
log.Fatal(err)
}
return db
}
func DoQuery() (ids []int) {
ids = nil
db := dbConn()
defer db.Close()
res, err := db.Query("select id from mytable where name=?", "Puppy")
if err != nil {
log.Fatal(err)
}
for res.Next() {
var id int
res.Scan(&id)
ids = append(ids, id)
}
return
}
func DoUpdate(id int) {
db := dbConn()
defer db.Close()
res, err := db.Exec("update mytable set name=? where id=?", "Kitty", id)
if err != nil {
log.Fatal(err)
}
count, err := res.RowsAffected()
if err != nil {
log.Fatal(err)
}
}
func main() {
ids := DoQuery()
for _, id := range ids {
DoUpdate(id)
}
}
No comments:
Post a Comment