Golang custom data type querying and inserting the point data in PostgreSQL
The specific code is as follows:
PackageMainImport("bytes" "Database/sql" "Database/sql/driver" "FMT"_"GITHUB.COM/LIB/PQ" "StrConv" "Strings")//Custom Support typetypePointstruct{Xfloat64 ' JSON: ' Lat 'Yfloat64 ' JSON: ' LNG '}//Implement driver. Valuer Interfacefunc(P *point) Value () (Driver. Value, error) {buf: =New(bytes. Buffer) fmt. fprintf (BUF,"(%f%f)", p.x, P.Y)returnBuf. Bytes (),Nil}func(P *point) String ()string{returnFmt. Sprintf ("(%v%v)", p.x, P.Y)}//Implement SQL. Scanner Interfacefunc(P *point) Scan (ValInterface{}) (err error) {ifbb, OK: = val. ([]uint8); OK {tmp: = bb[1:Len(BB)-1] Coors: = Strings. Split (string(tmp[:]),",")ifp.x, err = StrConv. Parsefloat (Coors[0], -); Err! =Nil{returnERR}ifP.Y, err = StrConv. Parsefloat (Coors[1], -); Err! =Nil{returnERR}}return Nil}typeAgentstruct{Idint ' JSON: ' ID 'Namestring ' JSON: ' Name 'Codestring ' JSON: ' Code 'Cs_nostring ' JSON: ' Cs_no 'channel_idint ' JSON: ' channel_id 'Addressstring ' JSON: ' Address 'Coordinate *point' JSON: ' point '}funcMain () {pgurl: = FMT. Sprintf ("Postgres://%s:%[email protected]%s:%s/%s?sslmode=disable","Postgres","123456","localhost","5432","People") db, err: = SQL. Open ("Postgres", Pgurl)ifErr! =Nil{Panic(FMT. Errorf ("Connection Database error:%v", err)} Querysql: =' SELECT * from T_agent 'Rows, err: = db. Query (Querysql)ifErr! =Nil{Panic(FMT. Errorf ("Error querying Data:%v", err))} forRows. 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)}varIdintErr = 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)}
You need to implement SQL when the field type requires a scan that supports queries. Scanner interface
You need to implement driver when the field type needs to support insertion. Valuer interface
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Golang custom data type querying and inserting the point data in PostgreSQL