Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Created September 27, 2015 12:26
Show Gist options
  • Save hirokazumiyaji/5642fb21fff7c8bae40f to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/5642fb21fff7c8bae40f to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"fmt"
"flag"
_ "github.com/go-sql-driver/mysql"
)
type User struct {
ID int
Email string
AccountName string
NickName string
}
type Profile struct {
UserID int
FirstName string
LastName string
Sex string
Birthday string
Pref string
Updated string
}
var (
db *sql.DB
userStmt *sql.Stmt
profileStmt *sql.Stmt
dumpType = flag.Int("dump", 1, "dump type 1 = user, 2 = profile")
)
func init() {
var err error
db, err = sql.Open("mysql", "root:@/isucon5q")
if err != nil {
panic(err)
}
userStmt, err = db.Prepare(
`SELECT id, email, account_name, nick_name FROM users`,
)
if err != nil {
panic(err)
}
profileStmt, err = db.Prepare(
`SELECT user_id, first_name, last_name, sex, birthday, pref, updated_at FROM profiles`,
)
if err != nil {
panic(err)
}
}
func main() {
flag.Parse()
if dumpType == 1 {
rows, err := userStmt.Query()
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
user := User{}
err = rows.Scan(
&user.ID,
&user.Email,
&user.AccountName,
&user.NickName,
)
if err != nil {
panic(err)
}
fmt.Printf(
"%s\t%s\t%s\t%s\n",
user.ID,
user.Email,
user.AccountName,
user.NickName,
)
}
} else {
rows, err := profileStmt.Query()
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
profile := Profile{}
err = rows.Scan(
&profile.UserID,
&profile.FirstName,
&profile.LastName,
&profile.Sex,
&profile.Birthday,
&profile.Pref,
&profile.Updated,
)
if err != nil {
panic(err)
}
fmt.Printf(
"%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
profile.UserID,
profile.FirstName,
profile.LastName,
profile.Sex,
profile.Birthday,
profile.Pref,
profile.Updated,
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment