Created
September 6, 2015 07:19
-
-
Save trkrameshkumar/f4f1c00ef5d578561c96 to your computer and use it in GitHub Desktop.
Get get number of rows using sql in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
_ "github.com/lib/pq" | |
) | |
const ( | |
DB_USER = "ramesh" | |
DB_PASSWORD = "secret" | |
DB_NAME = "test_db" | |
) | |
func main() { | |
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", | |
DB_USER, DB_PASSWORD, DB_NAME) | |
db, err := sql.Open("postgres", dbinfo) | |
checkErr(err) | |
defer db.Close() | |
rows, err := db.Query("SELECT COUNT(*) as count FROM table_name") | |
fmt.Println("Total count:",checkCount(rows)) | |
checkErr(err) | |
} | |
func checkCount(rows *sql.Rows) (count int) { | |
for rows.Next() { | |
err:= rows.Scan(&count) | |
checkErr(err) | |
} | |
return count | |
} | |
func checkErr(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
var count int
stmt, err = db.Prepare("SELECT COUNT(*) as count FROM YourTable")
if err != nil { log.Fatal(err) }
err = stmt.QueryRow().Scan(&count)
if err != nil { log.Fatal(err) }
log.Println(count)
stmt.Close() // or use defer rows.Close(), idc
Refference:
Go database/sql tutorial
The code here by trkrameshkumar
is great though if you need to use the count functions often in various situations. WIll minimize your code, and make it more readable.
Cheers
Hi guys,
I am using the function checkCount() and it works fine.
The thing is when I call it twice in a row, the second time it returns 0.
I guess rows is not reset, is there a easy way to make the method reusable ?
Sorry if it 's a dumb question, It's literally my second day with GoLang
it is very goods!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@betasve What, why does Query have to be avoided for results that return only one row? I have code that is working that queries a lookup table and panics if there is more than one entry. I don't see anything in the docs to suggest that is a problem. Furthermore, the QueryRow documentation says
Expected to return, but not required to return. I read that to say there could be duplicates and there is no way to tell. I think it is just a convenience function.