当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO DB.QueryContext用法及代码示例


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

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 DB.QueryContext。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。