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