-1

I currently have:

func foo (w http.ResponseWriter, req *http.Request) {
    chekr := `SELECT FROM public."Users" WHERE email=$1`
    err = db.QueryRow(chekr, usr.Email).Scan()
    if err != sql.ErrNoRows {
        data, err := json.Marshal("There is already a user with this email")
        if err != nil { w.Write(data) }
    }
    // code that should run if email isn't found
}

However, I find it never working and always passing the if block.

  • You miss *something* between `SELECT` and `FROM`. Maby `SELECT * FROM ...`, or `SELECT 1 FROM ...` if you don't care about the result values. – GMB Sep 12 '20 at 00:36
  • @GMB is on the right direction. Make sure your chekr is a valid Postgres SQL SELECT – Steve Wilhelm Sep 12 '20 at 01:35
  • https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS – mkopriva Sep 12 '20 at 03:43
  • 1
    The error handling makes no sense. Just because there's no ErrNoRows doesn't mean it worked. There can be any number of other errors. Also, you're writing your error message only if encoding it fails. – Peter Sep 12 '20 at 04:31

1 Answers1

-1

As the above comment stated, I forgot the */1. QueryRow works, I just had another error somewhere. As others have stated there's others errors, this is just for one case to test.

  • 1
    That does not sound right. [The implementation](https://golang.org/src/database/sql/sql.go?s=47327:47389#L1709) for `QueryRow` just calls `QueryRowContext` so the only difference between the two is that you can pass a context into `QueryRowContext`. The [docs](https://golang.org/pkg/database/sql/#DB.QueryRow) state "the *Row's Scan will return ErrNoRows" and I've just successfully tested this. – Brits Sep 12 '20 at 02:05
  • 1
    https://play.golang.org/p/CA-CQj-S7Ox Note that you can use [raw strings](https://golang.org/ref/spec#String_literals) (i.e. `\`text surrounded by backticks\``) to avoid having to escape double quotes. Note also that in the given example there is no benefit in creating the prepared statement manually and immediately closing it, the `(*sql.DB).QueryXxx` methods already do that underneath *when* the query takes arguments. Prepared statements make sense, AFAICT, only when you need to execute them more than once. – mkopriva Sep 12 '20 at 03:58
  • Sorry, I stand corrected. I further read into it and found that the error would occur with QueryRow I must have had an error in my previous code. As far as error handling this was a sample to test ONE condition that I knew wasn't working. You should use a switch like they used in the docs. I appreciate the info on the Close() stmt, I just used what was on the documentation and it showed them using it. – Nathan Takemori Sep 12 '20 at 22:13