How to get number of rows by select query using mysql

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")


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 

Tags:

Mysql

Rows

Go