dreinuqm992401
2016-01-02 06:33
浏览 70

golang mysql未定义:sql.Query

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条回答 默认 最新

  • drix47193 2016-01-02 06:53
    已采纳

    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()
    
    打赏 评论

相关推荐 更多相似问题