返回SQL查询的结果映射。

huangapple go评论96阅读模式
英文:

GO: Return map from SQL query

问题

我正在一个GO函数中查询一个MySQL数据库,并希望以键值对的形式在一个map中返回结果,但是我还不能完全弄清楚如何实现。到目前为止,我有以下函数:

func GetData(callIds []string) map[string]Records {
    //db insert
    db, err := sql.Open("mysql", mySql)
    if err != nil {
        fmt.Printf(err.Error())
    }
    defer db.Close()
    //db query
    var foo string
    err = db.QueryRow("select foo from bardata where callId = %v", 1).Scan(&foo)
    if err != nil {
        fmt.Printf(err.Error())
    }
    fmt.Println(foo)

    return nil
}

我想要返回一个map,其中键是callId,值是从查询结果中返回的foo

英文:

I am querying a mysql database in a GO function and want to return key value pairs in a map but can't quite figure out how to accomplish this. So far I have this function:

func GetData(callIds []string) map[string]Records {
	//db insert
	db, err := sql.Open("mysql", mySql)
	if err != nil {
		fmt.Printf(err.Error())
	}
	defer db.Close()
	//db query
	var foo string
	err = db.QueryRow("select foo from bardata where callId = %v", 1).Scan(&foo)
	if err != nil {
		fmt.Printf(err.Error())
	}
	fmt.Println(foo)

	return nil

I want to return a map with the key being callId and value being foo for each row returned from the query.

答案1

得分: 1

首先,你需要构建查询语句。目前来看,你甚至没有使用函数的输入。由于参数的数量是可变的,我们需要做一些工作来构建正确数量的占位符:

query := `select callid, foo from bardata where callid in (` +
    strings.Repeat(`?,`, len(callIds) - 1) + `?)`

然后,使用传入的值执行查询:

rows, err := db.Query(query, callIds...)
if err != nil {
    // 处理错误
}
defer rows.Close()

接着收集结果:

ret := map[string]string{}
for rows.Next() {
    var callid, foo string
    err = rows.Scan(&callid, &foo)
    if err != nil {
        // 处理错误
    }
    ret[callid] = foo
}

return ret

注意事项:

  1. 如果callIds是一个空切片,这将导致占位符不匹配错误。如果可能的话,你需要单独检测并处理它(例如通过返回错误或空映射来处理——不一定需要查询数据库)。

  2. 这里返回的是一个map[string]string,其中值是"foo"的内容。在你的问题中,函数返回了一个map[string]Records,但是没有提供关于Records是什么或如何获取它的信息。

  3. 你可能希望将sql.ErrNoRows与其他错误分开处理。

英文:

First, you need to build up your query. As it is, you're not even using your function input. Since we have a variable number of arguments, we need to do a little work to construct the right number of placeholders:

query := `select callid, foo from bardata where callid in (` +
    strings.Repeat(`?,`, len(callIds) - 1) + `?)`

then, execute with the values passed in:

rows, err := db.Query(query, callIds...)
if err != nil {
    // handle it
}
defer rows.Close()

then collect the results:

ret := map[string]string{}
for rows.Next() {
    var callid, foo string
    err = rows.Scan(&callid, &foo)
    if err != nil {
        // handle it
    }
    ret[callid] = foo
}

return ret

Caveats:

  1. This will cause a placeholder mismatch error if callIds is an empty slice. If that's possible, then you need to detect it and handle it separately (maybe by returning an error or an empty map — querying the DB shouldn't be necessary).

  2. This returns a map[string]string where the values are whatever "foo" is. In your question you have the function returning a map[string]Records but there's no information about what a Records might be or how to fetch one.

  3. You might want to handle sql.ErrNoRows differently from other errors.

答案2

得分: 0

以下是翻译好的代码部分:

package main

import (
	"fmt"
	"github.com/bobby96333/goSqlHelper"
)

func main(){
	fmt.Println("hello")
	conn,err :=goSqlHelper.MysqlOpen("user:password@tcp(127.0.0.1:3306)/dbname")
	checkErr(err)
	row,err := conn.QueryRow("select * from table where col1 = ? and  col2 = ?","123","abc")
	checkErr(err)
	if *row==nil {
		fmt.Println("no found row")
	}else{
		fmt.Printf("%+v",row)
	}
}

func checkErr(err error){
	if err!=nil {
		panic(err)
	}
}

输出结果:

&map[col1:abc col2:123]

英文:
package main

import (
	"fmt"
	"github.com/bobby96333/goSqlHelper"
)

func main(){
	fmt.Println("hello")
	conn,err :=goSqlHelper.MysqlOpen("user:password@tcp(127.0.0.1:3306)/dbname")
	checkErr(err)
	row,err := conn.QueryRow("select * from table where col1 = ? and  col2 = ?","123","abc")
	checkErr(err)
	if *row==nil {
		fmt.Println("no found row")
	}else{
		fmt.Printf("%+v",row)
	}
}

func checkErr(err error){
	if err!=nil {
		panic(err)
	}
}

output:

&map[col1:abc col2:123]

huangapple
  • 本文由 发表于 2016年1月3日 02:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/34569181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定