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

How to Count Rows in a Database Using Go?

Linda Hamilton
Release: 2024-11-05 18:20:02
Original
619 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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