Skip to content

Instantly share code, notes, and snippets.

@wendal
Created July 31, 2012 06:10
Show Gist options
  • Save wendal/3214184 to your computer and use it in GitHub Desktop.
Save wendal/3214184 to your computer and use it in GitHub Desktop.
Golang操作MySQL
package main
import "database/sql"
import _ "code.google.com/p/go-mysql-driver/mysql"
import "encoding/json"
import "fmt"
type User struct {
User string `json:"user"`
Password string `json:"password"`
Host string `json:"host"`
}
func main() {
db, e := sql.Open("mysql", "root:123456@tcp(localhost:3306)/mysql?charset=utf8")
if e != nil {
print("ERROR?")
}
_, e2 := db.Query("select 1")
if e2 == nil {
println("DB OK")
rows, e := db.Query("select user,password,host from mysql.user")
if e != nil {
fmt.Print("query error!!%v\n", e)
return
}
if rows == nil {
print("Rows is nil")
return
}
for rows.Next() {
user := new(User)
row_err := rows.Scan(&user.User,&user.Password, &user.Host)
if row_err != nil {
print("Row error!!")
return
}
b, _ := json.Marshal(user)
fmt.Println(string(b))
}
println("Done")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment