How to get number of rows by select query using mysql

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

How to get number of rows by select query using mysql

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是golang的新手。我想从MySQL数据库中创建一个登录验证。
我想要一个像PHP中的mysqli_num_rows($res) == 1这样的方法...
我尝试了len(rows)rows.Column()以及fmt.Println("No of rows are :", rows),但都不起作用...
以下是我尝试的代码(这只是一个虚拟代码):

rows, err := db.Query("select * from userLog where u_name = ? and u_pass = ?", uname, pswd)
if err != nil {
    log.Fatal(err)
}
fmt.Println("No of rows are :", rows)
defer rows.Close()

如果你对登录验证有其他解决方案,请提供建议并简要解释一下。请帮助我。

英文:

I'm new in golang. I want to create a login verification from MySQL db.
I want a method like as in PHP mysqli_num_rows($res) == 1...
I tried len(rows) or rows.Column() @fmt.Println("No of rows are :", rows) but it won't...
The code which i tried ... (It is a dummy code)

rows, err := db.Query("select * from userLog where u_name = ? and u_pass = ?", uname, pswd)
if err != nil {
    log.Fatal(err)
}
fmt.Println("No of rows are :", rows)
defer rows.Close()

If you have another solution for login verification purpose then kindly suggest and explain it briefly Kindly help me out.

答案1

得分: 10

根据我的理解,您需要检查用户和密码是否存在于数据库中。如果存在,您可以执行以下操作:

var isAuthenticated bool
err := db.QueryRow("SELECT IF(COUNT(*),'true','false') FROM userLog WHERE u_name = ? AND u_pass = ?", uname, pswd).Scan(&isAuthenticated)
if err != nil {
    log.Fatal(err)
}

如果数据库中包含提供的用户名和密码,isAuthenticated 将被设置为 true

英文:

As i understand it you need to check if user and password exist in database. If so you can do:

var isAuthenticated bool
err := db.QueryRow("SELECT IF(COUNT(*),'true','false') FROM userLog WHERE u_name = ? AND u_pass = ?", uname, pswd).Scan(&isAuthenticated)
if err != nil {
    log.Fatal(err)
} 

If database contains supplied user and password isAuthenticated will be set to true.

答案2

得分: 6

如果你已经执行了一个查询 db.Query("SELECT * FROM some_tbl") 并且有一个 rows 迭代器,那么你无法在不迭代的情况下提取行数。正如你所看到的没有任何返回行数的方法

所以你唯一能做的就是查询选择行数:db.Query("SELECT COUNT(*) FROM some_tbl")

英文:

If you already executed a query db.Query("SELECT * FROM some_tbl") and have a rows iterator, then you can't extract the number of rows without iterating through it. As you see there nothing that returns the number of rows.

So the only thing you can do is to make a query to select the number of rows: db.Query("SELECT COUNT(*) FROM some_tbl")

答案3

得分: 5

以下是一个相当高效的方法,用于在Go语言中返回MySQL查询结果的行数:

rows, selerr := db.Query(sql, StartDate, EndDate) // 查询
if selerr != nil { 
    fmt.Fprint(w, selerr); 
    return 
}
count := 0
for rows.Next() { 
    count += 1 
}

rows, _ := db.Query(sql, StartDate, EndDate) // 再次查询 - 没有错误
英文:

Here is a fairly efficient way to return the number of rows in a MySQL select in go:

rows, selerr := db.Query(sql, StartDate, EndDate) // Query
if selerr != nil { 
    fmt.Fprint(w, selerr); 
    return 
}
count := 0
for rows.Next() { 
    count += 1 
}

rows, _ := db.Query(sql, StartDate, EndDate) // Query again - no error 

答案4

得分: 4

如上所述,count(*) 可以正常工作,而 Scan 则使其更简单,例如:

func GetCount(schemadottablename string) int {
    var cnt int
    _ = db.QueryRow(`select count(*) from ` + schemadottablename).Scan(&cnt)
    return cnt 
}

当然,你可以使用 where 语句来“细化”计数,例如:

func GetCount(schemadottablename string, column string, value string) int {
    var cnt int
    _ = db.QueryRow(`select count(` + column + `) from ` + schemadottablename + ` where ` + column + `=?`, value).Scan(&cnt)
    return cnt 
}
英文:

As mentioned, count(*) works fine and Scan makes it simpler still, e.g.:

func GetCount(schemadottablename string) int {
    var cnt int
    _ = db.QueryRow(`select count(*) from ` + schemadottablename).Scan(&cnt)
    return cnt 
}

You can, of course, use this with a where statement to "refine" the count, e.g.:

func GetCount(schemadottablename string, column string, value string) int {
    var cnt int
    _ = db.QueryRow(`select count(` + column + `) from ` + schemadottablename + ` where ` + column + `=?`, value).Scan(&cnt)
    return cnt 

}

答案5

得分: 0

应用程序的语言并不重要。使用count(*)

select count(*) as cnt
from userLog
where u_name = ? and u_pass = ?;

然后读取查询返回的值。

英文:

The application language doesn't make a different. Use count(*):

select count(*) as cnt
from userLog
where u_name = ? and u_pass = ?;

Then read the value that the query returns.

答案6

得分: 0

只是为了增加对这个主题的一些见解,你是否考虑过像拥有一个通用的方案一样,允许你将任何select语句转换为select count(*),这可能在分页操作中很有用,也有希望满足某人的需求:

package main

import (
	"fmt"
	"regexp"
)

const sample = `select a,b,c
from <table>
where <conditions>`

func main() {
	var re = regexp.MustCompile(`(select)\b.[\s\S]*(from[\s\S]*)`)
	s := re.ReplaceAllString(sample, "$1 count(*)\n$2")
	fmt.Println(sample + "\n")
	fmt.Println(s)
}

链接

英文:

Just to add some insight into this subject, have you thought like having a general recipe that allows you to express any select statement into select count(*), that might be useful in pagination affairs and hopefully on what someone is looking for:

package main

import (
	&quot;fmt&quot;
	&quot;regexp&quot;
)

const sample = `select a,b,c
from &lt;table&gt;
where &lt;conditions&gt;`

func main() {
	var re = regexp.MustCompile(`(select)\b.[\s\S]*(from[\s\S]*)`)
	s := re.ReplaceAllString(sample, &quot;$1 count(*)\n$2&quot;)
	fmt.Println(sample + &quot;\n&quot;)
	fmt.Println(s)
}

https://play.golang.org/p/29Iiv1Ta-0_D

huangapple
  • 本文由 发表于 2015年10月10日 23:16:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/33055527.html
匿名

发表评论

匿名网友

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

确定