kkirsche
kkirsche

Reputation: 1257

Golang Go-SQLite3 cannot iterate over type error

When attempting to use the examples from github.com/mattn/go-sqlite3's repository, I get the following error when trying to compile the code with Go 1.5.1 darwin/amd64:

non-bool rows.Next() (type error) used as for condition

The code I'm using is:

conn, err := sqlite3.Open("./example.db")
if err != nil {
    log.Panic(err)
}
defer conn.Close()
rows, err := conn.Query("SELECT * FROM scans ORDER BY id DESC;")
if err != nil {
    log.Panic(err)
}
for rows.Next() {
    var id int
    var method string
    var uuid string
    var scan int
    rows.Scan(&id, &method, &uuid, &scan)
    log.Print(id, method, uuid, scan)
}

Is there something which I am missing here? This is based on the example found here: https://github.com/mattn/go-sqlite3/blob/master/_example/simple/simple.go#L81-L91

Upvotes: 3

Views: 619

Answers (1)

icza
icza

Reputation: 417512

Yes, you are missing.

You are not using the database/sql package but you are using the sqlite3 package!


sql.Open() returns an sql.DB, DB.Query() returns an sql.Rows, and Rows.Next() is:

func (rs *Rows) Next() bool

But instead you call sqlite3.Open() which returns an sqlite3.Conn, then you call Conn.Query() which returns an sqlite3.Stmt which you name rows! So rows.Next() is Stmt.Next() which is:

func (s *Stmt) Next() error

Source of confusion

It is confusing because sqlite3 is a driver conforming to the built-in database/sql interface, but it also provides another interface and you used it via its vendor-specific sqlite3 interface.

Using the database/sql package you would start it like this:

db, err := sql.Open("sqlite3", "./foo.db")

Upvotes: 4

Related Questions