package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"learngo/mysql/model"
)
func main() {
var product model.Product
db, err := sql.Open("mysql", "root:123456@tcp(localhost:3306)/laravel_admin?charset=utf8")
if err != nil {
fmt.Println(">>> fail to connect to db <<<")
}
defer db.Close()
fmt.Println(">>> succeed to connect to db <<<")
//查询的字段数量 顺序 要与后面 一致
err = db.QueryRow("select `name`,`price`,`created_at`,`intro`,`id` from product where id =?", 4).Scan(&product.Name, &product.Price, &product.CreatedAt, &product.Intro, &product.Id)
if err != nil {
fmt.Println(err)
}
fmt.Println(product.Name.String)
}
//model-product
type Product struct {
Id int64 `json:"id"`
Name sql.NullString `json:"name"`
Price float64 `json:"pricename"`
Intro sql.NullString `json:"intro"`
CreatedAt sql.NullString `json:"created_at"`
}