Golang泛型方法从数据库中获取数据

时间:2016-02-27 02:32:02

标签: generics go datatables gorp

我正在尝试在Golang中实现jquery datatables server side processing。部分需要通用方法从DB中选择数据。我已经发布了我在下面所做的简化版本。

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)
}

一旦我运行它,就会抛出以下错误,

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

根据错误,Select()不接受接口。是否有可能在golang中实现这种普遍性?感谢您是否可以指导我这项工作?

1 个答案:

答案 0 :(得分:2)

在这种情况下,结果已经是指针(用户作为&用户传递),因此您不需要再次获取它的地址。

替换行:

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

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