Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
On this page

type DB

Updated on 2024-08-20 GMT+08:00

The following table describes type DB.

Method

Description

Return Value

(db *DB)Begin()

Starts a transaction. The isolation level of the transaction is determined by the driver.

*Tx and error

(db *DB)BeginTx(ctx context.Context,

opts *TxOptions)

Starts a transaction with a specified transaction isolation level. A specified context is used until the transaction is committed or rolled back. If the context is canceled, the SQL package rolls back the transaction.

*Tx and error

(db *DB)Close()

Closes the database and releases all the opened resources.

error

(db *DB)Exec(query string,

args ...interface{})

Performs an operation that does not return rows of data.

Result and error

(db *DB)ExecContext(ctx context.Context,

query string, args ...interface{})

Performs an operation that does not return rows of data in a specified context.

Result and error

(db *DB)Ping()

Checks whether the database connection is still valid and establishes a connection if necessary.

error

(db *DB)PingContext(ctx context.Context)

Checks whether the database connection is still valid in a specified context and establishes a connection if necessary.

error

(db *DB)Prepare(query string)

Creates a prepared statement for subsequent queries or executions.

*Stmt and error

(db *DB)PrepareContext(ctx context.Context, query string)

Creates a prepared statement for subsequent queries or executions in a specified context.

*Stmt and error

(db *DB)Query(query string,

args ...interface{})

Executes a query and returns multiple rows of data.

*Rows and error

(db *DB)QueryContext(ctx context.Context,

query string, args ...interface{})

Executes a query and returns multiple rows of data in a specified context.

*Rows and error

(db *DB)QueryRow(query string,

args ...interface{})

Executes a query that returns only one row of data.

*Row

(db *DB)QueryRowContext(ctx context.Context,

query string, args ...interface{})

Executes a query that returns only one row of data in a specified context.

*Row

Parameters

Parameter

Description

ctx

Specified context.

query

Executed SQL statement.

args

Parameter that needs to be bound to the executed SQL statement. Binding by location and binding by name are supported. For details, see Examples.

opts

Transaction isolation level and transaction access mode. The transaction isolation level (opts.Isolation) supports sql.LevelReadUncommitted, sql.LevelReadCommitted, sql.LevelRepeatableRead, and sql.LevelSerializable. The transaction access mode (opts.ReadOnly) can be true (read only) or false (read write).

NOTICE:
  1. The Query(), QueryContext(), QueryRow(), and QueryRowContext() APIs are usually used in query statements, such as SELECT. The Exec() API is used for executing operation statements. If query APIs are used to execute non-query statements, the execution result may be unexpected. Therefore, you are advised not to use the query APIs to execute non-query statements, such as UPDATE and INSERT.
  2. The result of executing a query statement using a query API needs to be obtained through the Next() API in type Rows. If the result is not obtained through the Next() API, unexpected errors may occur.

Examples

// In this example, the username and password are stored in environment variables. Before running this example, set environment variables in the local environment (set the environment variable names based on the actual situation).
package main
// Set the dependency package based on the dependency package path in the environment.
import (
 "database/sql"
 _ "gitee.com/opengauss/openGauss-connector-go-pq"
 "log"
)

func main() {
        hostip := os.Getenv("GOHOSTIP")   // GOHOSTIP indicates the IP address written into the environment variable.
        port := os.Getenv("GOPORT")       // GOPORT indicates the port number written into the environment variable.
        usrname := os.Getenv("GOUSRNAME") // GOUSRNAME indicates the username written into the environment variable.
        passwd := os.Getenv("GOPASSWD")   // GOPASSWDW indicates the user password written into the environment variable.
        str := "host=" + hostip + " port=" + port + " user=" + usrname + " password=" + passwd + " dbname=gaussdb sslmode=disable"
 db, err := sql.Open("gaussdb", str)
 if err != nil {
  log.Fatal(err)
 }
 defer db.Close()

 err = db.Ping()
 if err != nil {
  log.Fatal(err)
 }

 _, err = db.Exec("create table test_bound(id int, name text)")

	// Binding by location
	_, err = db.Exec("insert into test_bound(id, name) values(:1, :2)", 1, "Zhang San")
 if err != nil {
  log.Fatal(err)
 }

	// Binding by name
	_, err = db.Exec("insert into test_bound(id, name) values(:id, :name)", sql.Named("id", 1), sql.Named("name", "Zhang San"))
 if err != nil {
  log.Fatal(err)
 }
}

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback