I am very new to Golang and am using the PQ package for postgres. What I am trying to do is prevent duplicate emails, so I have a query that checks to see if a user email is already 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")
}
That is my code above how can I make it such that I can check like this
if rows >0 { ...}
when I try to do that I get the error
invalid operation: rows > 0 (mismatched types sql.Result and int)
How can I solve this issue as I been looking around to resolve it for a bit now.
What's happening here is that you've told Go that your query won't be returning any rows (see docs for Exec())
You should probably use either:
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()
will return nil
- rows.Err()
should also be called to check for errors.
Please also note the other answer from BJ Black - the check_duplicate_emails.Exec(email)
line is also wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With