英文:
Go, Golang : fetchall for go MySQL?
问题
我正在使用go-mysql-driver https://github.com/go-sql-driver/mysql。
我正在寻找Python中类似以下代码的解决方案:
c = conn.cursor()
c.execute(sql)
result = c.fetchall()
for elem in result:
list.append(elem[i])
return list
我能想到的唯一方法是:
result, err := conn.Exec(query)
// func (db *DB) Exec(query string, args ...interface{}) (Result, error)
我想遍历Exec方法返回的结果,然后获取数据。
英文:
I am using the go-mysql-driver https://github.com/go-sql-driver/mysql
I am looking for something like the following in Python:
c = conn.cursor()
c.execute(sql)
result = c.fetchall()
for elem in result:
list.append(elem[i])
return list
And the only thing that comes to my mind is:
result, err := conn.Exec(query)
// func (db *DB) Exec(query string, args ...interface{}) (Result, error)
I want to traverse through the results from the Exec method and then fetch the data.
答案1
得分: 2
如果你对结果感兴趣,应该使用Query()
而不是Exec()
:
rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Printf("%s is %d\n", name, age)
}
请注意,这是一个Go语言的示例代码,用于从数据库中查询用户的姓名。
英文:
If you are interested in the result you should use Query()
instead of Exec()
:
rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
if err != nil {
log.Fatal(err)
}
defer rows.Close();
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
log.Fatal(err)
}
fmt.Printf("%s is %d\n", name, age)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论