Golang中无法定义Query变量的问题。

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

golang sqlite can't define Query variable

问题

似乎 golang 的 sqlite 包不喜欢我的 db.Query 语句,尽管它与 GitHub 上的示例 中的语句完全相同。

db, err := sql.Open("sqlite3", "./database.db")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

rows, err = db.Query("select id, name from job")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

fmt.Println("Jobs:")
for rows.Next() {
    var name string
    var id int
    fmt.Printf("%v %v\n", id, name)
}

这是我得到的错误:

./test.go:7: undefined: rows
./test.go:7: cannot assign to rows
./test.go:11: undefined: rows
./test.go:14: undefined: rows

编辑:我也尝试过使用重音符和单引号字符串来调用 db.Query(),但没有成功。

英文:

It seems golang's sqlite package doesn't like my db.Query statement, though it's exactly like the one found in the example on github.

db, err := sql.Open("sqlite3", "./database.db")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

rows, err = db.Query("select id, name from job")
if err != nil {
    log.Fatal(err)
}   
defer rows.Close()

fmt.Println("Jobs:")
for rows.Next() {
    var name string
    var id int
    fmt.Printf("%v %v\n", id, name)
}  

This is the error I'm getting:

./test.go:7: undefined: rows
./test.go:7: cannot assign to rows
./test.go:11: undefined: rows
./test.go:14: undefined: rows

Edit: I've tried using grave accent and single quote strings for db.Query() as well, to no avail.

答案1

得分: 4

你不能给未声明的变量赋值。

rows, err = db.Query("select id, name from job")

应该改为:

rows, err := db.Query("select id, name from job")

理论上这应该解决问题,但我还没有尝试过。

你还应该添加:

rows.Scan(&id, &name)

在printf函数之前,这样才能将行的值分配给id和name变量,否则将打印一个空字符串和0。

英文:

You cannot assign values to to undeclared variables.

rows, err = db.Query("select id, name from job")

Should be :

rows, err := db.Query("select id, name from job")

Theoretically this should solve the problem, but I haven't tried.

You should also add :

rows.Scan(&id, &name)

Before the printf function so as to actually assign the row's value to the id & name variables otherwise will print an empty string & 0.

huangapple
  • 本文由 发表于 2014年8月21日 03:28:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/25412930.html
匿名

发表评论

匿名网友

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

确定