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

时间:2015-12-12 03:49:37

标签: go sqlite

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

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

id传递给运行查询的函数。

如何从result检索计数值?

1 个答案:

答案 0 :(得分:1)

这应该有效:

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