计算golang中的行数 [英] Count number of rows in golang

查看:261
本文介绍了计算golang中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Go显示数据库中的行数.如何显示行数?

I want to display the number of rows from database using Go. How do I display number of rows?

count, err := db.Query("SELECT COUNT(*) FROM main_table")

推荐答案

查询将在变量计数中返回一行.因此,下一个要做的就是使用功能Scan()读取此行并将结果分配到新变量中.这是这样的.

The query will return a row into the variable count. So the next you have to do is to read this row and assign the result into a new variable, using the function Scan(). This is how it works.

rows, err := db.Query("SELECT COUNT(*) FROM main_table")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

var count int

for rows.Next() {   
    if err := rows.Scan(&count); err != nil {
        log.Fatal(err)
    }
}

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

最好的选择是使用QueryRow(),因为您希望只读取一行.这样的代码将是.

The best option thought would be to use QueryRow() as you expect to read just one row. The code then will be.

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)
}

这篇关于计算golang中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆