简体   繁体   中英

golang sqlite can't define Query variable

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM