英文:
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
注意事项:
-
如果
callIds
是一个空切片,这将导致占位符不匹配错误。如果可能的话,你需要单独检测并处理它(例如通过返回错误或空映射来处理——不一定需要查询数据库)。 -
这里返回的是一个
map[string]string
,其中值是"foo"的内容。在你的问题中,函数返回了一个map[string]Records
,但是没有提供关于Records
是什么或如何获取它的信息。 -
你可能希望将
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:
-
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). -
This returns a
map[string]string
where the values are whatever "foo" is. In your question you have the function returning amap[string]Records
but there's no information about what aRecords
might be or how to fetch one. -
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论