du16178 2016-08-17 10:43
浏览 56
已采纳

Jmoiron SQLX Golang通用接口

I am new to golang and using Jmoiron Sqlx package for querying the Postgres Database(select query) . The waY I am doing is creating a sql string and calling Select(dest interface{}, query string,args) method. While it works well , the problem is I am generating my sql String dynamically and as such the destination structure should be different for each response .

For ex : - One query can be

Select a,b,c,d from table A ;

the other can be

Select x,y,z from Table B;

From what i understand , there should be two different structs defined for Select Method to work i.e.

Struct Resp1{
   a string
   b string
   c  string
   d string
}

And,

Struct Resp2{
   x string
   y string
   z  string

}

And then invoke select as db.Select(&resp1,query,args) and db.Select(&resp2,query,args) I am thinking if its possible for me to define a common Struct

say Resp3{
   a string
   b string
   c  string
   d string
   x string
   y string
   z  string
}

And based on my select query populates only the matching columns (i.e only a,b,c,d for first and x,y,z for second) .

I tried searching but couldnt get any leads .

  • 写回答

2条回答 默认 最新

  • doudian6229 2016-08-23 15:13
    关注

    I could not get answer to this here and since I needed this , I dug up myself and I found how to solve this in an efficient way .

    To solve this one can define all your String values as sql.NullString , integer as sql.int64 , float as sql.float64 etc .

    So Say your table is having columns a,b,c,d,e,f and for some response you only have to display a,b,d for some other d,e and so on . Instead of creating different structures and mapping them in db.Select(...) statement Just define ur struct as follows

    a       sql.NullString `json:"whatever u wish to have as key,omitempty"`
    b       sql.NullString `json:"b,omitempty"`
    c       sql.NullString `json:"c,omitempty"`
    d       sql.int64  `json:"d,omitempty"`
    e       sql.float64  `json:"e,omitempty"`
    

    Remember sql.NullString will be Marshalled to json with an additional key displayed (Valid:boolean) . You can follow approach here to fix that How can I work with sql NULL values and JSON in Golang in a good way?

    Hope this is helpful to someone.!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值