golang reflect for sql scan 报错

/**

-- name is character varying(64)

CREATE TABLE users

(

  id bigint NOT NULL,

  no character(24),

  identity name,

  name name,

  head character varying(256),

  email character varying(256),

  site character varying(256),

  create_time timestamp without time zone,

  city_id bigint,

  timezone jsonb,

  update_time timestamp without time zone,

  CONSTRAINT user__pk PRIMARY KEY (id)

)


spottly=# SELECT "id", "no", "identity", "name", "head", "email", "site", "create_time", "city_id", "update_time", "timezone" FROM "users" WHERE "email" = 'fixopen@yeah.net' LIMIT 1 OFFSET 0;

       id       | no | identity |  name   |                  head                  |      email       |            site            | create_time | city_id | update_time | timezone

----------------+----+----------+---------+----------------------------------------+------------------+----------------------------+-------------+---------+-------------+----------

 95083655397376 |    | fixopen  | fixopen | /uploader/52e2762edf4e633666000867.png | fixopen@yeah.net | http://spottly.com/fixopen |             |         |             |

(1 row)

*/


package main


import (

    "database/sql"

    //"errors"

    "fmt"

    _ "github.com/lib/pq"

    "log"

    "net/url"

    "reflect"

    "strings"

    "time"

)


type User struct {

    Id          uint64    `json:"id"`

    No          *string   `json:"no"`

    Identity    string    `json:"identity"`

    Name        string    `json:"name"`

    Head        url.URL   `json:"head"`

    Email       *string   `json:"email"`

    Site        url.URL   `json:"site"`

    Create_time time.Time `json:"create-time"`

    City_id     *uint64   `json:"city-id"`

    Update_time time.Time `json:"update-time"`

    Timezone    *string   `json:"timezone"`

}


func main() {

    connectionString := "host=localhost port=5432 user=postgres dbname=spottly password=123456 sslmode=disable"

    db, err := sql.Open("postgres", connectionString)

    defer db.Close()

    if err != nil {

        log.Fatal(err)

    }



浮云间
浏览 159回答 1
1回答

料青山看我应如是

url.URL没有实现sql.Scanner,所以它不能从数据库扫描。您可以制作一个确实实现的包装器类型sql.Scanner:type sqlURL struct { url.URL }func (su *sqlURL) Scan(v interface{}) error {    u, err := url.Parse(string(v.([]byte)))    if err != nil {        return err    }    *su = sqlURL{*u}    return nil}或者将URL单独扫描成字符串然后解析:var urlStr stringerr = db.QueryRow(command).Scan(/* ... */, &urlStr)// check erru, err := url.Parse(urlStr)// check erruser.Site = *u
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go