英文:
Reading Database Rows into map[string]string
问题
我想从一个简单的SQL表中读取结果,就像下面这样:
customer | key |
---|---|
A | 12345 |
B | 6789 |
现在,我想构建一个map[string]string
,其中的键值对等于行的值,如下所示:
map[A:12345, B:6789]
然而,我在只获取查询结果的值并动态创建键值对方面遇到了问题。我将提供代码的大致概述(SQL连接部分不是问题,我已经解决了):
import "database/sql"
func main() {
// 一些连接到MSSQL的代码...
db, _ := sql.Open("mssql", connString)
stmt := "SELECT customer, key from tbl"
rows, _ := db.Query(stmt)
defer rows.Close()
data := make(map[string]string)
for rows.Next() {
// 需要在这里帮助我获取每一行的键值对并将它们添加到我的map中...
}
}
我也可以尝试使用一个空结构体,其中字段成为结果集的第一列(动态的),值成为结果集的第二列。
英文:
I would like to read results from a simple SQL table like the following
customer | key |
---|---|
A | 12345 |
B | 6789 |
Now, I'd like to structure a map[string]string
which has key value pairs equal to the row values like such:
map[A:12345, B:6789]
However, I am having trouble just taking the values out of the query result and dynamically creating the key-val pairs. I'll provide a rough outline of the code (the SQL connection stuff is not an issue, I have that figured out)
import "database/sql"
func main() {
// Some code to connect to MSSQL...
db, _ := sql.Open("mssql", connString)
stmt := "SELECT customer, key from tbl"
rows, _ := db.Query(stmt)
defer rows.Close()
data := make(map[string]string)
for rows.Next() {
// Need help here grabbing each row pair and adding them to my map...
}
}
I'm open to trying to do this with an Empty struct as well, where the fields become the first column of my result set (dynamic) and the value becomes the 2nd column of my result set.
答案1
得分: 2
你可以暂时将这些值存储在两个变量中,然后将它们存储在map中:
func main() {
stmt := "SELECT customer, key from tbl"
rows, _ := db.Query(stmt)
defer rows.Close()
data := make(map[string]string)
var (
consumer string
key string
)
for rows.Next() {
if err := rows.Scan(&consumer, &key); err != nil {
// 处理错误
}
data[consumer] = key
}
for k, v := range data {
fmt.Println(k, v)
}
// "A" "12345"
// "B" "6789"
}
请注意,consumer
和key
变量在循环外部分配,以便我们可以重复使用它们。即使值是空字符串,这些变量在每次迭代时也会被覆盖。
英文:
You could temporarily store the values in two variables and then store them in the map:
func main() {
stmt := "SELECT customer, key from tbl"
rows, _ := db.Query(stmt)
defer rows.Close()
data := make(map[string]string)
var (
consumer string
key string
)
for rows.Next() {
if err := rows.Scan(&consumer, &key); err != nil {
// Handle err
}
data[consumer] = key
}
for k, v := range data {
fmt.Println(k, v)
}
// "A" "12345"
// "B" "6789"
}
Note that the consumer
and key
variables are allocated outside of the loop so we can re-use them. Even if the values are empty strings, the variables will be overwritten on each iteration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论