Skip to content

Instantly share code, notes, and snippets.

@Hunk13
Forked from rameshkumarxyz/db.go
Created May 26, 2021 16:34
Show Gist options
  • Select an option

  • Save Hunk13/bbac2f719eb58017a479297b71c90650 to your computer and use it in GitHub Desktop.

Select an option

Save Hunk13/bbac2f719eb58017a479297b71c90650 to your computer and use it in GitHub Desktop.
Get get number of rows using sql in golang
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment