douchi2022 2014-11-23 22:48
浏览 46
已采纳

SELECT导致的Golang Gorp错误

I am trying to do a SELECT from mySQL database with GORP. I am getting an error which says "reflect.Value.Interface: cannot return value obtained from unexported field or method". I have verified the DB connectivity. For example Select (*) count gives the right count. I see that it fails on

dbmap.Select(&dd, "SELECT * FROM kd_dropdowns")

Without the above line program does not throw any error.

Here is my code.

package main
import (
"database/sql"
"fmt"
"log"
"net/http"

"github.com/coopernurse/gorp"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)

func main() {

fmt.Println("reached main")
// Create a MUX
r := mux.NewRouter()

//manegala patti
r.HandleFunc("/manegalu", manegalaTorisu).Methods("GET")

http.ListenAndServe(":8080", r)

}
func manegalaTorisu(w http.ResponseWriter, r *http.Request) {
type Dropdowns struct {
    dd_id      int64  `db:"dd_id"`
    identifier int64  `db:"identifier"`
    name       string `db:"name"`
    active     string `db:"active"`
}

db, err := sql.Open("mysql", "krishna:xxxx@/kd")
defer db.Close()

var dbmap *gorp.DbMap
// construct a gorp DbMap
dbmap = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{}}

var dd []Dropdowns
_, err = dbmap.Select(&dd, "SELECT * FROM kd_dropdowns")
checkErr(err, "Select failed")
fmt.Fprint(w, "Success")
}

func checkErr(err error, msg string) {
if err != nil {
    log.Fatalln(msg, err)
}
}

This is how table looks in mySQL

  • 写回答

1条回答 默认 最新

  • doulu2011 2014-11-24 11:27
    关注

    This is a common trap for people starting with Go.

    All the fields in a struct are exported or hidden simply based on the first letter: if it is uppercase, the field is exported. Otherwise, it is not.

    Gorp is trying to access the exported fields in your struct. But you've used lowercase first-letters, so the fields are hidden and so it fails.

    Try this instead.

    ...
    type Dropdowns struct {
        DdId       int64  `db:"dd_id"`
        Identifier int64  `db:"identifier"`
        Name       string `db:"name"`
        Active     string `db:"active"`
    }
    ...
    

    You can camelcase your dd_id as DdId if you prefer (I think this is more idiomatic in Go).

    Note that the uppercase export feature of Go applies to constants, package variables, types and function names, as well as the fields within structs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法