0

I have a piece of code that checks whether or not the requested key exists in the database. Its contents are therefore not important in that particular place.

The best way I know how to check for it is to try to Scan() it and see if it returned an error, which leaves the declared and initialized variable which it scanned into unused. My question is, is this the cleanest and most minimal way to solve that problem?

Relevant code (using database/sql from the standard library):

var content string
err := db.QueryRowContext(
    ctx,
    querySelect,
    hashKey,
).Scan(&content)

return err == nil

Scanning into io.Discard doesn't work here as it reports "destination not a pointer".

vatuqemor
  • 9
  • 2
  • 1
    Use `SELECT EXISTS(...)`. See [1](https://stackoverflow.com/a/49449519/965900), [2](https://stackoverflow.com/a/54753257/965900). – mkopriva Jul 28 '22 at 04:01
  • I've accidentally discovered that `Scan(nil)` seemingly works. I guess now it's between checking for two types of errors that `Scan()` can then return or making a slightly longer query with the `SELECT 1` solution. – vatuqemor Jul 28 '22 at 04:29

0 Answers0