如何从go-sqlite3查询中获取计数值?

huangapple go评论79阅读模式
英文:

How to get the count value from a go-sqlite3 query?

问题

我正在使用go-sqlite3来检索具有特定值的列的行数:

query := "select count(notebook) from pages where notebook="
result, err := db.Query(fmt.Sprint(query, id))

其中id是传递给运行查询的函数的参数。

我该如何从result中检索计数值?

英文:

I am using go-sqlite3 to retrieve the number of rows with a column of a certain value:

query := "select count(notebook) from pages where notebook="
result, err := db.Query(fmt.Sprint(query, id))

Where id is passed to the function running the query.

How can I retrieve the count value from result?

答案1

得分: 4

这应该可以工作:

// 输出将存储在这里。
var output string

id := "1234"

 // 准备查询
query, err := db.Prepare("select count(notebook) from pages where notebook = ?")

if err != nil {
	fmt.Printf("%s", err)
}

defer query.Close()

// 使用'id'执行查询,并将值放入'output'中
err = query.QueryRow(id).Scan(&output)

// 捕获错误
switch {
case err == sql.ErrNoRows:
        fmt.Printf("没有该ID的笔记本。")
case err != nil:
        fmt.Printf("%s", err)
default:
        fmt.Printf("计算了%s个笔记本\n", output)
}
英文:

This should work:

// Output will be stored here.
var output string

id := "1234"

 // Prepare your query
query, err := db.Prepare("select count(notebook) from pages where notebook = ?")

if err != nil {
	fmt.Printf("%s", err)
}

defer query.Close()

// Execute query using 'id' and place value into 'output'
err = query.QueryRow(id).Scan(&output)

// Catch errors
switch {
case err == sql.ErrNoRows:
        fmt.Printf("No notebook with that ID.")
case err != nil:
        fmt.Printf("%s", err)
default:
        fmt.Printf("Counted %s notebooks\n", output)
}

huangapple
  • 本文由 发表于 2015年12月12日 11:49:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/34236038.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定