dscw1223 2014-03-25 02:28 采纳率: 50%
浏览 69

将结构映射到mysql表,并将行绑定到结构

This is my first script using go-sql-driver.

My mysql table (PRODUCT) looks like:

id int
name varchar(255)
IsMatch tinyint(1)
created datetime

I want to simply load a row from a table, and bind it to a struct.

I have this so far:

package main

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

type Product struct {
    Id    int64
  Name  string
  IsMatch ??????????
  Created ?????
}

func main() {
    fmt.Printf("hello, world!
")

    db, err := sql.Open("mysql", "root:@/product_development")
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

    rows, err := db.Query("SELECT * FROM products where id=1")
    if err != nil {
        panic(err.Error()) // proper error handling instead of panic in your app
    }

}

Now I need to:

1. What datatype in Go do I use for tinyint and datetime?
2. How to I map the rows to a Product struct?
  • 写回答

2条回答 默认 最新

  • douhuang3740 2014-03-25 06:38
    关注

    What datatype in Go do I use for tinyint and datetime?

    For a hint as to the types that the database/sql package will be using, have a look at the documentation for database/sql.Scanner, which lists the Go types used within database/sql itself:

    int64
    float64
    bool
    []byte
    string
    time.Time
    nil - for NULL values
    

    This would lead you to try int64 for IsMatch and time.Time for Created. I believe in reality you can use pretty much any sized int (maybe even bool, you'd have to check the source) for IsMatch because it can be stored "without loss of precision." The documentation for go-mysql-driver explains that you will need to add parseTime=true to your DSN in order for it to parse into a time.Time automatically or use NullTime.

    How to I map the rows to a Product struct?

    It should be something pretty strightforward, using Rows.Scan, like:

    var products []*Product
    for rows.Next() {
        p := new(Product)
        if err := rows.Scan(&p.ID, &p.Name, &p.IsMatch, &p.Created); err != nil { ... }
        products = append(products, p)
    }
    if err := rows.Err() { ... }
    

    This scans the columns into the fields of a struct and accumulates them into a slice. (Don't forget to Close the rows!)

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?