bvpx
bvpx

Reputation: 1287

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.

Upvotes: 0

Views: 1463

Answers (1)

Marc
Marc

Reputation: 1820

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.

Upvotes: 4

Related Questions