dreinuqm992401 2016-01-02 06:33
浏览 78
已采纳

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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求购HI3519AV100开发板
  • ¥15 请问1553 RT怎么测试,没有BC有方法吗
  • ¥100 业务编程如何选择学习方向和内容?
  • ¥15 wamp3.3.5安装完成后图标正常显示绿色,鼠标左右键点击图标均无反应。求解决方法。
  • ¥15 鼠标点击的这条记录了什么?
  • ¥15 在写pid调速的程序时,电机始终维持最大速度
  • ¥15 【有偿】调用DXGI截图初始化失败,提示0xf 887a0004
  • ¥15 请问如何查看手机root记录?
  • ¥15 商城小程序订单号重复
  • ¥15 学校优化算法sbo和蚁群算法怎么结合