golang mysql undefined:sql.Query

时间:2016-01-02 06:33:41

标签: mysql go

我正在尝试执行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 :=
我错过了什么?我知道代码中还有其他错误,但只是尝试调试/学习。

1 个答案:

答案 0 :(得分:1)

查看documentationOpen返回指向数据库的"指针",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()