英文:
Golfing postgres how can I return count number from the query
问题
我对Golang非常陌生,正在使用PQ包处理PostgreSQL。我想要做的是防止重复的电子邮件,所以我有一个查询来检查用户的电子邮件是否已经存在于数据库中。
这是我的代码,我该如何修改才能进行如下检查:
if rows > 0 { ... }
当我尝试这样做时,我得到了错误:
invalid operation: rows > 0 (mismatched types sql.Result and int)
我该如何解决这个问题?我已经找了一段时间了,但还没有解决。
英文:
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.
答案1
得分: 3
这里的情况是,你告诉Go语言,你的查询不会返回任何行(参见Exec()的文档)。
你可能应该使用以下两种方式之一:
-
"select somecol from ... where ..." 不包含 count(*) 查询,使用 Query,然后查看 rows.Next() 来判断是否有第一行。
英文:
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:
答案2
得分: 1
根据文档的说明,你需要调用rows.Next()
并检查其是否成功:
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")
}
如果没有数据,rows.Next()
将返回nil
,还应调用rows.Err()
来检查错误。
还请注意BJ Black的另一个答案 - check_duplicate_emails.Exec(email)
这一行也是错误的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论