Golang Custom Data Type query and insertion of point data in postgresql, golangpostgresql
Golang Custom Data Type query and insertion of point data in postgresql
The Code is as follows:
Package mainimport ("bytes" "database/SQL" "database/SQL/driver" "fmt" _ "github.com/lib/pq" "strconv" "strings ") // custom supported types: type Point struct {X float64 'json: "lat" 'Y float64' json: "lng" '} // implement driver. valuer interface func (p * Point) Value () (driver. value, error) {buf: = new (bytes. buffer) fmt. fprintf (buf, "(% f)", p. x, p. y) return buf. bytes (), nil} func (p * Point) String () string {return fmt. sprintf ("(% V % v) ", p. x, p. y)} // implement SQL. callback interface 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 ("database connection error: % v", err)} querySql: = 'select * FROM t_agent 'rows, err: = db. query (querySql) if err! = Nil {panic (fmt. errorf ("Data Query error: % 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 )"). scan (& id) fmt. println ("id:", id, "err:", err )}
When the field type needs to support the query scan, you need to implement the SQL. Seek Interface
When the field type needs to support insertion, the driver. Valuer interface must be implemented
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.