英文:
golang mysql undefined: sql.Query
问题
我正在尝试执行类似以下的 Golang 数据库查询:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var (
name string
id int
age int
)
func main() {
db, err := sql.Open("mysql", "dbaccess:dbaccess@/dbaccess")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query("SELECT * FROM people WHERE id = ?", 1)
if err != nil {
panic(err.Error())
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
panic(err.Error())
}
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
panic(err.Error())
}
}
但是我得到了以下错误:
20: undefined: sql.Query
我尝试在等号前面加上冒号,但是又得到了以下错误:
20: no new variables on left side of :=
我错过了什么?我知道代码中还有其他错误,但我只是想在调试/学习过程中找出问题所在。
英文:
I'm trying to do a golang db query like:
package main
import "fmt"
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
var (
name string
id int
age int
)
func main() {
rows, err := sql.Open("mysql", "dbaccess:dbaccess@/dbaccess")
if err != nil {
panic(err.Error())
}
defer rows.Close()
rows, err = sql.Query("select * from people where id = ?", 1)
if err != nil {
panic(err.Error())
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&id, &name)
if err != nil {
panic(err.Error())
}
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
panic(err.Error())
}
}
But I get the error:
20: undefined: sql.Query
I tried to put a colon before = but then got an error:
20: no new variables on left side of :=
what am I missing? I know there are other errors in the code, but just trying to debug/learn as I go.
答案1
得分: 3
看一下文档。Open
返回一个“指向数据库的指针”,Query
是使用这个指针的方法(而不是 SQL)。所以你需要像这样做:
db, err := sql.Open("mysql", "dbaccess:dbaccess@/dbaccess")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query("select * from people where id = ?", 1)
if err != nil {
panic(err.Error())
}
defer rows.Close()
英文:
Look at the documentation. Open
returns a "pointer to a database", Query
is a method that uses this pointer (and not sql). So you need to do something like this:
db, err := sql.Open("mysql", "dbaccess:dbaccess@/dbaccess")
if err != nil {
panic(err.Error())
}
defer rows.Close()
rows, err := db.Query("select * from people where id = ?", 1)
if err != nil {
panic(err.Error())
}
defer rows.Close()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论