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.
Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).
The COUNT (*) function returns the number of rows that satisfy the WHERE clause of a SELECT statement. The following example finds how many rows in the stock table have the value HRO in the manu_code column: SELECT COUNT(*) FROM stock WHERE manu_code = 'HRO';
Getting MySQL row count of two or more tables To get the row count of multiple tables, you use the UNION operator to combine result sets returned by each individual SELECT statement.
In MySQL, the COUNT() function calculates the number of results from a table when executing a SELECT statement. It does not contain NULL values. The function returns a BIGINT value. It can count all the matched rows or only rows that match the specified conditions.
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
}
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.
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")
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