golang自訂資料類型查詢與插入postgresql中point資料,golangpostgresql

來源:互聯網
上載者:User

golang自訂資料類型查詢與插入postgresql中point資料,golangpostgresql
golang自訂資料類型查詢與插入postgresql中point資料

具體代碼如下:

package mainimport (    "bytes"    "database/sql"    "database/sql/driver"    "fmt"    _ "github.com/lib/pq"    "strconv"    "strings")// 自訂支援類型type Point struct {    X float64 `json:"lat"`    Y float64 `json:"lng"`}// 實現driver.Valuer介面func (p *Point) Value() (driver.Value, error) {    buf := new(bytes.Buffer)    fmt.Fprintf(buf, "(%f %f)", p.X, p.Y)    return buf.Bytes(), nil}func (p *Point) String() string {    return fmt.Sprintf("(%v %v)", p.X, p.Y)}// 實現sql.Scanner介面func (p *Point) Scan(val interface{}) (err error) {    if bb, ok := val.([]uint8); ok {        tmp := bb[1 : len(bb)-1]        coors := strings.Split(string(tmp[:]), ",")        if p.X, err = strconv.ParseFloat(coors[0], 64); err != nil {            return err        }        if p.Y, err = strconv.ParseFloat(coors[1], 64); err != nil {            return err        }    }    return nil}type Agent struct {    Id         int    `json:"id"`    Name       string `json:"name"`    Code       string `json:"code"`    CS_NO      string `json:"cs_no"`    Channel_id int    `json:"channel_id"`    Address    string `json:"address"`    Coordinate *Point `json:"point"`}func main() {    pgurl := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", "postgres", "123456", "localhost", "5432", "people")    db, err := sql.Open("postgres", pgurl)    if err != nil {        panic(fmt.Errorf("串連資料庫出錯:%v", err))    }    querySql := `SELECT * FROM t_agent`    rows, err := db.Query(querySql)    if err != nil {        panic(fmt.Errorf("查詢資料出錯:%v", err))    }    for rows.Next() {        agent := &Agent{Coordinate: &Point{}}        err = rows.Scan(&agent.Id,            &agent.Name, &agent.Code,            &agent.CS_NO, &agent.Channel_id,            &agent.Address, agent.Coordinate)        fmt.Println(agent, err)    }    var id int    err = db.QueryRow("INSERT INTO t_agent (name, code, cs_no, address, coordinate) VALUES($1,$2,$3,$4,$5) RETURNING id",        "test1", "123457", "2", "111", "(12,43)").Scan(&id)    fmt.Println("id:", id, "err:", err)}

欄位類型需要支援查詢的scan時,需要實現sql.Scanner介面
欄位類型需要支援插入時,需要實現driver.Valuer介面

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.