GO語言"database/sql"包中"DB.QueryContext"類型的用法及代碼示例。
用法:
func(db *DB) QueryContext(ctx context.Context, query string, args ...any)(*Rows, error)
QueryContext 執行返回行的查詢,通常是 SELECT。 args 用於查詢中的任何占位符參數。
例子:
package main
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
)
var (
ctx context.Context
db *sql.DB
)
func main() {
age := 27
rows, err := db.QueryContext(ctx, "SELECT name FROM users WHERE age=?", age)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
names := make([]string, 0)
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
// Check for a scan error.
// Query rows will be closed with defer.
log.Fatal(err)
}
names = append(names, name)
}
// If the database is being written to ensure to check for Close
// errors that may be returned from the driver. The query may
// encounter an auto-commit error and be forced to rollback changes.
rerr := rows.Close()
if rerr != nil {
log.Fatal(rerr)
}
// Rows.Err will report the last error encountered by Rows.Scan.
if err := rows.Err(); err != nil {
log.Fatal(err)
}
fmt.Printf("%s are %d years old", strings.Join(names, ", "), age)
}
相關用法
- GO DB.QueryRowContext用法及代碼示例
- GO DB.Query用法及代碼示例
- GO DB.ExecContext用法及代碼示例
- GO DB.BeginTx用法及代碼示例
- GO DB.Prepare用法及代碼示例
- GO DB.PingContext用法及代碼示例
- GO DecodeLastRuneInString用法及代碼示例
- GO DumpResponse用法及代碼示例
- GO Date用法及代碼示例
- GO Dial用法及代碼示例
- GO Decoder.Token用法及代碼示例
- GO Decoder.Decode用法及代碼示例
- GO DumpRequest用法及代碼示例
- GO Drawer用法及代碼示例
- GO Duration.Hours用法及代碼示例
- GO Duration.Round用法及代碼示例
- GO DecodeRuneInString用法及代碼示例
- GO DumpRequestOut用法及代碼示例
- GO DecodeRune用法及代碼示例
- GO Duration用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 DB.QueryContext。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。