sqlx返回空结构,即使它存在

时间:2019-01-28 20:43:51

标签: go sqlx

这是我的代码:

package main

import (
    "fmt"
    "github.com/jmoiron/sqlx"
    _ "github.com/lib/pq"
    "log"
    "time"
)

type Commune struct {
    Id int `db:"id"`
    Created time.Time `db:"created"`
    Modified time.Time `db:"modified"`
    Name string `db:"name"`
}

func main() {
    var err error
    db, err = sqlx.Connect("postgres", "user=toto 
    dbname=tata password=titi sslmode=disable")
    commune := []Commune{}
    db.Select(&commune, `SELECT * FROM "Geo_commune"  WHERE id=1  ORDER BY name ASC`)
    rows, err2 := db.Query(`SELECT * FROM "Geo_commune"  WHERE id=1  ORDER BY name ASC`)
    fmt.Println(commune)
    fmt.Println(rows)
    if err != nil {
    log.Fatalln(err)
    }
     if err2 != nil {
    log.Fatalln(err2)
    }

   }

这是数据库中的数据:

enter image description here

edit:table_name:

enter image description here

我什至尝试过:

db.Select(&commune, `SELECT * FROM "Geo_commune"  WHERE id=1  ORDER BY name ASC`)

但是返回总是空的,我确定数据存在并且我没有连接错误。

没有"Geo_commune"  行,err2:= db.Query(SELECT * FROM Geo_commune WHERE id=1 ORDER BY name ASC) 我有一个 : 2019/01/28 22:17:16 pq:关系“ geo_commune”不存在

致谢

编辑我的新测试:

package main

import (
    "fmt"
    "github.com/jmoiron/sqlx"
    "log"
    "time"
    _ "github.com/lib/pq"
)
type Commune struct {
    Id int `db:"id"`
    Created time.Time `db:"created"`
    Modified time.Time `db:"modified"`
    Name string `db:"name"`

}
var db *sqlx.DB
func main() {
    var err error
    db, err = sqlx.Connect("postgres", "user=toto dbname=titi password=tata sslmode=disable")
    commune := []Commune{}

    if err != nil {
        log.Fatalln(err)
    }
    db.Select(&commune, `SELECT * FROM "Geo_commune"  WHERE id=1  ORDER BY name ASC`)
    rows, err2 := db.Query(`SELECT * FROM "Geo_commune"  WHERE id=1  ORDER BY name ASC`)
    if err != nil {
        log.Fatalln(err)
    }
    if err2 != nil {
        log.Fatalln(err2)
    }


    db.Select(&commune, `SELECT * FROM public.Geo_commune  WHERE id=1  ORDER BY name ASC`)
    rows, err2 = db.Query(`SELECT * FROM public.Geo_commune  WHERE id=1  ORDER BY name ASC`)
    fmt.Println(commune)
    fmt.Println(rows)
    if err != nil {
        log.Fatalln(err)
    }
    if err2 != nil {
        log.Fatalln(err2)
    }



    }

给我:

[]
<nil>
2019/01/29 09:50:06 pq: relation "public.geo_commune" does not exist

1 个答案:

答案 0 :(得分:0)

我对您的描述感到困惑。 它抛出了pq: relation "geo_commune" does not exist吗? 如果是这样,则您的数据源不正确。 如果没有,请尝试select * from public.Geo_commune