dsx58940 2016-02-27 02:32
浏览 225
已采纳

Golang从数据库获取数据的通用方法

I'm trying to implement the jquery datatables server side processing in Golang. Part of that needs a generic method to select data from DB. I've posted a simplified version of what I've done below.

package main
import (
    "gopkg.in/gorp.v1"
    "database/sql"
  _ "github.com/go-sql-driver/mysql"
)

type User struct {
    TenantId     int     `db:"tenantid"json:"tenantid"`
    Username     string  `db:"username"json:"username"`
    Password     string  `json:"password"`
}


func GenericSelect(database string,  table string, columns []string, result interface{})interface{} {
    dbMap := getDBConnection(database);
    defer dbMap.Db.Close()
    var err error
    query := "SELECT " 

    for index,element := range columns {
      query += element
      if(index+1 != len(columns)){
        query += ","
      }
    }
    query +=  " FROM " + table + " LIMIT 1,100"
    _, err = dbMap.Select(&result, query)
    if err != nil {
        panic(err.Error())  // Just for example purpose.
    }
  return result
}


func getDBConnection(dbname string) *gorp.DbMap {
    var connectionUrl string
    connectionUrl = "root:root@tcp(localhost:3306)/" + dbname

    db, err := sql.Open("mysql", connectionUrl)
    if err != nil {
        panic(err.Error())  // Just for example purpose.
    }
    dbmap := &gorp.DbMap{Db: db, Dialect:gorp.MySQLDialect{"InnoDB", "UTF8"}}
    return dbmap
}


func main(){
        var users []User
        columns := []string{"tenantid", "username", "password"}
        result := GenericSelect("portal","accounting",columns, &users)
        //make result in to a json instead of print
        print(result)
}

Once I run this, it throws the following error,

panic: gorp: Cannot SELECT into this type: *interface {}

goroutine 1 [running]:
main.GenericSelect(0x6b1c30, 0x6, 0x6bd490, 0xa, 0xc208073f60, 0x3, 0x3, 0x5e8e60, 0xc20801e260, 0x0, ...)
    /home/anuruddha/Desktop/go-lang/main.go:30 +0x37f

According to the error, Select() is not accepting interfaces. Is it possible to achieve this level of generality in golang? Appreciate if you can direct me to get this working?

  • 写回答

1条回答 默认 最新

  • dongliao8069 2016-02-27 02:41
    关注

    In this case result is already a pointer (users is passed as &users), so you don't need to take the address of it again.

    Replace the line:

    _, err = dbMap.Select(&result, query)
    

    with

    _, err = dbMap.Select(result, query)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择