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

import "time"

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.")
}

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

上一篇:百场ORACLE OCP题库解析,CUUG你值得信赖!


下一篇:sqlmap基础用法