Golf trip, how can I return a number from a request

I am very new to Golang and I use the PQ package for postgres. What I'm trying to do is to prevent duplicate emails, so I have a query that checks if the user email is in the database

check_duplicate_emails, err := db.Prepare("select count(*) from profiles where email=$1") rows, err := check_duplicate_emails.Exec(email) if rows != nil { fmt.Fprintf(w,"Duplicate Email") } 

This is my code above, how can I make it so that I can check it like

 if rows >0 { ...} 

when i try to do this i get an error

invalid operation: rows> 0 (inconsistent sql.Result and int types)

How can I solve this problem since I was looking for it to solve it now.

+5
source share
2 answers

Looking at the documentation , you need to call rows.Next() and check that it succeeds:

 if rows.Next() { fmt.Fprintf(w, "Duplicate Email") } else if rows.Err() { fmt.Fprintf(w, "Oops, error %s", rows.Err()) } else { fmt.Fprintf(w, "OK, unique email address") } 

If there is no data, rows.Next() nil - rows.Err() is rows.Err() to check for errors.

Also, pay attention to another answer from BJ Black - the line check_duplicate_emails.Exec(email) also incorrect.

+1
source

What happens is that you told Go that your request would not return strings (see docs for Exec () )

You should probably use either:

  • a combination of QueryRow and Scan () (an example in QueryRow is a good one), or
  • a "select somecol from ... where ..." without querying count (*) with Query and look at rows.Next () to see if there was a first row.
+3
source

Source: https://habr.com/ru/post/1257364/


All Articles