我正在尝试执行如下 golang 数据库查询:
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())
}
}
但是我得到了错误:
20: undefined: sql.Query
我试图在 = 之前放一个冒号,但随后出现错误:
20: no new variables on left side of :=
我错过了什么?我知道代码中还有其他错误,但我只是尝试调试/学习。
最佳答案
查看documentation . Open
返回一个“指向数据库的指针”,Query
是使用这个指针(而不是 sql)的方法。所以你需要做这样的事情:
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()
关于mysql - golang mysql undefined : sql. 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34563303/