英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论