golang mysql undefined: sql.Query 翻译结果: golang mysql 报错:undefined: sql.Query

huangapple go评论89阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2016年1月2日 14:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/34563303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定