Home > Backend Development > Golang > How to Count Rows in a Go Database?

How to Count Rows in a Go Database?

Barbara Streisand
Release: 2024-11-05 22:58:02
Original
1007 people have browsed it

How to Count Rows in a Go Database?

Counting Rows in Go

Retrieving the count of rows from a database is a fundamental operation in Go applications. One approach is to use the db.Query function to execute a raw SQL query. By setting the query to SELECT COUNT(*) FROM you can fetch the row count.

<code class="go">count, err := db.Query("SELECT COUNT(*) FROM main_table")</code>
Copy after login

However, you'll need to scan the returned row to access the actual count value.

<code class="go">var rowCount int
if err := rows.Scan(&rowCount); err != nil {
    log.Fatal(err)
}</code>
Copy after login

You can then print the rowCount:

<code class="go">fmt.Printf("Number of rows are %s\n", rowCount)</code>
Copy after login

For simplicity, it's recommended to use db.QueryRow instead of db.Query in this scenario, as you expect only one row to be returned.

<code class="go">var rowCount int
err := db.QueryRow("SELECT COUNT(*) FROM main_table").Scan(&rowCount)</code>
Copy after login

By using QueryRow(), you can avoid closing the result and handle the error gracefully using switch:

<code class="go">switch {
case err != nil:
    log.Fatal(err)
default:
    fmt.Printf("Number of rows are %s\n", rowCount)
}</code>
Copy after login

This provides a concise and efficient way to retrieve row counts from a database in Go.

The above is the detailed content of How to Count Rows in a Go Database?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template