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

How to Count Rows in a Database Using Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 18:20:02675browse

How to Count Rows in a Database Using Go?

Count Number of Rows in a Database Using Go

In Go, to display the number of rows from a database, a common approach is to use the Query() function in the database/sql package. This function executes a query and returns a Result object, which can be iterated over to access the rows returned by the query.

To count the number of rows, you can use the following steps:

<code class="go">// Execute the query to retrieve row count
rows, err := db.Query("SELECT COUNT(*) FROM main_table")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

// Initialize a variable to store the count
var count int

// Loop through the rows
for rows.Next() {
    // Read the count into the variable
    if err := rows.Scan(&count); err != nil {
        log.Fatal(err)
    }
}

fmt.Printf("Number of rows are %s\n", count)</code>

For greater efficiency, you can use the QueryRow() function if you only expect to retrieve a single row, like this:

<code class="go">var count int

err := db.QueryRow("SELECT COUNT(*) FROM main_table").Scan(&count)
switch {
case err != nil:
    log.Fatal(err)
default:
    fmt.Printf("Number of rows are %s\n", count)
}</code>

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

Statement:
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