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 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
it is very goods!