Go的mysql库的使用:连接和查询

import (
      "time"
      _ "github.com/go-sql-driver/mysql"
)


type User struct {
    Id        int
    Uuid      string
    Name      string
    Email     string
    Password  string
    CreatedAt time.Time
}

const (
    MySQLHost = "127.0.0.1"
    MySQLPort = "3306"
    MySQLUser = "usr"
    MySQLPasswd = "passwd"
    MySQLDBName = "dbname"
)

func main() {
    MySQLInfo := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", MySQLUser, MySQLPasswd, MySQLHost, MySQLPort, MySQLDBName)
    Db, err := sql.Open("mysql", MySQLInfo)
    if err != nil {
        log.Fatal(err)
        return
    }
    _ = Db
    rows, err := Db.Query("SELECT id, uuid, name, email, created_at FROM users")
    if err != nil {
       log.Fatal(err)
       return
    }
    users := make([]User, 0)
    count := 0
    for rows.Next() {
        user := User{}
        var createAt string
        err = rows.Scan(&user.Id, &user.Uuid, &user.Name, &user.Email, &createAt)
        fmt.Println(createAt)
        user.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createAt)
        users = append(users, user)
        count++
    }
    fmt.Println(count, len(users))
    for i, _ := range users {
        user := users[i]
       fmt.Println(user.Id, user.Uuid, user.Name, user.Email, user.CreatedAt)
    }
    fmt.Println("connect success.")
}
posted @ 2020-09-15 17:33  飞天小烤猪  阅读(271)  评论(0编辑  收藏  举报