GO語言"database/sql"包中"DB.Query"類型的用法及代碼示例。
用法:
func(db *DB) Query(query string, args ...any)(*Rows, error)
Query 執行返回行的查詢,通常是 SELECT。 args 用於查詢中的任何占位符參數。
查詢在內部使用 context.Background;要指定上下文,請使用QueryContext
示例(多個結果集):
package main
import (
"context"
"database/sql"
"log"
)
var (
ctx context.Context
db *sql.DB
)
func main() {
age := 27
q := `
create temp table uid (id bigint); -- Create temp table for queries.
insert into uid
select id from users where age < ?; -- Populate temp table.
-- First result set.
select
users.id, name
from
users
join uid on users.id = uid.id
;
-- Second result set.
select
ur.user, ur.role
from
user_roles as ur
join uid on uid.id = ur.user
;
`
rows, err := db.Query(q, age)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var (
id int64
name string
)
if err := rows.Scan(&id, &name); err != nil {
log.Fatal(err)
}
log.Printf("id %d name is %s\n", id, name)
}
if !rows.NextResultSet() {
log.Fatalf("expected more result sets: %v", rows.Err())
}
var roleMap = map[int64]string{
1: "user",
2: "admin",
3: "gopher",
}
for rows.Next() {
var (
id int64
role int64
)
if err := rows.Scan(&id, &role); err != nil {
log.Fatal(err)
}
log.Printf("id %d has role %s\n", id, roleMap[role])
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
相關用法
- GO DB.QueryRowContext用法及代碼示例
- GO DB.QueryContext用法及代碼示例
- 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.Query。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。