高尔夫球的PostgreSQL,我如何从查询中返回计数数字?

huangapple go评论78阅读模式
英文:

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()的文档)。

你可能应该使用以下两种方式之一:

  • QueryRowScan() 的组合(QueryRow中有一个很好的示例),或者

  • "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:

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

答案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.

huangapple
  • 本文由 发表于 2016年9月28日 09:11:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/39736530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定