Updated on 2025-09-04 GMT+08:00

Detailed Procedure

  1. Obtain the variable values needed by connection parameters and concatenate them to create a connection string.

    • The connection string can be in DSN or URL format.
    • For details about database connection parameters, refer to "Application Development Guide > Development Based on the Go Driver > Development Procedure > Preparing the Environment" in Developer Guide.

    The parameter values involved in Detailed Procedure can be obtained from the environment variables set in Preparations and concatenated, as shown in the following code. You can obtain the values of connection parameters from environment variables by using os.Getenv. Alternatively, you can set these values by reading configuration files or writing fixed values.

    hostip := os.Getenv("GOHOSTIP")                   // GOHOSTIP: IP address written to environment variables.
    port := os.Getenv("GOPORT")                       // GOPORT: port number written to environment variables.
    usrname := os.Getenv("GOUSRNAME")                 // GOUSRNAME: username written to environment variables.
    passwd := os.Getenv("GOPASSWD")                   // GOPASSWD: user password written to environment variables.
    dbname := os.Getenv("GODBNAME")                   // GODBNAME: name of the target database written to environment variables.
    connect_timeout := os.Getenv("GOCONNECT_TIMEOUT") // GOCONNECT_TIMEOUT: timeout interval for connecting to the database written to environment variables.
    socket_timeout := os.Getenv("GOSOCKET_TIMEOUT")   // GOSOCKET_TIMEOUT: maximum duration of the SQL statement written to environment variables.
    rootcertPath := os.Getenv("GOROOTCERT")           // GOROOTCERT: path to the root certificate written to environment variables.
    sslkeyPath := os.Getenv("GOSSLKEY")               // GOSSLKEY: path to the key of the client certificate written to environment variables.
    sslcertPath := os.Getenv("GOSSLCERT")             // GOSSLCERT: path to the client SSL certificate written to environment variables.
    sslmode := os.Getenv("GOSSLMODE")                 // GOSSLMODE: SSL encryption written to environment variables.
    • In case of a DSN connection string, refer to the following recommended connection settings and format when assigning values to the dsn variable:
      dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s connect_timeout=%s socketTimeout=%s sslmode=%s sslrootcert=%s sslkey=%s sslcert=%s target_session_attrs=master",
       hostip,
       port,
       usrname,
       passwd,
       dbname,
       connect_timeout,
       socket_timeout,
       sslmode,
       rootcertPath,
       sslkeyPath,
       sslcertPath,
      )
    • In case of a URL connection string, refer to the following recommended URL connection settings and format when assigning values to the url variable:
      url := fmt.Sprintf("gaussdb://%s:%s@%s:%s/%s?connect_timeout=%s&socketTimeout=%s&sslmode=%s&sslrootcert=%s&sslkey=%s&sslcert=%s&target_session_attrs=master",
       usrname,
       passwd,
       hostip,
       port,
       dbname,
       connect_timeout,
       socket_timeout,
       sslmode,
       rootcertPath,
       sslkeyPath,
       sslcertPath,
      )
    • connect_timeout: timeout interval (in seconds) for connecting to the database server. The timeout interval must be set based on the actual network conditions. A default value of 0 indicates that no timeout will occur.
    • socket_timeout: maximum duration of a single SQL statement. If a statement exceeds this limit, it will be interrupted and reconnected. You are advised to set this parameter based on service characteristics. If not specified, the default value 0 will be applied, indicating that no timeout will occur.
    • sslmode: specifies whether to enable SSL encryption.
    • target_session_attrs: connection type of the database. This parameter is used to identify the primary and standby nodes. The default value is any.

  2. Create a database connection object using the connection string concatenated in 1.

    Golang's database/sql standard library provides the sql.Open API for creating a database connection object. Upon completion, the API returns the database connection object and any error information.

    func Open(driverName, dataSourceName string) (*DB, error)
    • Define a DSN connection string as follows:
      db, err := sql.Open("gaussdb", dsn)
    • Define a URL connection string as follows:
      db, err := sql.Open("gaussdb", url)

  3. Create a transaction object using the database connection object created in 2.

    The database connection object provides the Begin API for creating a transaction object. Upon completion, the API returns the transaction object and any error information.

    func (db *DB) Begin() (*Tx, error)

    The following creates a transaction object and receives the transaction object through the tx variable:

    tx, err := db.Begin()

  4. Execute batch insertion using the transaction object created in 3.

    The Exec API is used as an example. For details, see "Application Development Guide > Development Based on the Go Driver > Go API Reference > type Tx" in Developer Guide.

    (tx *Tx)Exec(query string, args ...interface{})

    The Exec API is called to insert the user-specified data size into the employee table in batches by using the transaction object "tx" created in 3. This involves concatenating the SQL statement for batch insertion and passing the necessary values.

    employee := []struct {
     Name string
     Age  uint8
    }{{Name: "zhangsan", Age: 21}, {Name: "lisi", Age: 22}, {Name: "zhaowu", Age: 23}}
    
    batchSql := "INSERT INTO employee (name, age) VALUES "
    vals := []interface{}{}
    
    placeholders := ""
    for i, u := range employee {
     placeholders += "(?, ?)"
     if i < len(employee)-1 {
      placeholders += ","
     }
     vals = append(vals, u.Name, u.Age)
    }
    
    stmt := batchSql + placeholders
    result, err := tx.Exec(stmt, vals...)

  5. (Optional) Roll back the transaction using the transaction object created in 3.

    The transaction object provides the Rollback API for rolling back the transaction.

    func (tx *Tx) Rollback() error

    If an error occurs in the transaction, call the Rollback API of the transaction object "tx" created in 3 to roll back the transaction.

    tx.Rollback()

  6. Commit the transaction using the transaction object created in 3.

    The transaction object provides the Commit API for committing the transaction.

    func (tx *Tx) Commit() error

    Commit the transaction through the Commit API of the transaction object "tx" created in 3.

    err := tx.Commit()

  7. (Optional) Execute a query using the database connection object created in 2.

    Both the database object and the transaction object provide the Query API. For details, see "type DB" and "type Tx" under "Application Development Guide > Development Based on the Go Driver > Go API Reference" in Developer Guide.

    For example, call the Query API provided by the database object "db" created in 2 to query the batch insertion results in 4 and receive the result object through the "rows" variable.

    rows, err := db.Query("SELECT id, name, created_at FROM users;"

  8. (Optional) Obtain the column count and column name list in the result set using the result object in 7.

    The result object in 7 is of the Rows type in database/sql of Golang. This type provides a Columns API to return the list of column names in the query result set. For details, see "Application Development Guide > Development Based on the Go Driver > Go API Reference > type Rows".

    func (rs *Rows) Columns() ([]string, error) 

    The following calls the Columns API provided by the result object in 7 to obtain the list of queried column names and assign values to the columns variable.

    columns, err := rows.Columns()

    The column count in the result set can be obtained by calling the len function to calculate columns.

    len(columns)

  9. (Optional) Obtain metadata such as column types in the result set by using the result object in 7.

    The result object in 7 is of the Rows type in database/sql of Golang. This type provides a ColumnTypes API to return the list of column names in the query result set. For details, see "Application Development Guide > Development Based on the Go Driver > Go API Reference > type Rows".

    func (rs *Rows) ColumnTypes() ([]*ColumnType, error) 

    Obtain column information from the result in 7.

    The following calls the ColumnTypes API provided by the result object in 7 to obtain the list of queried column types ([]*ColumnType) and assign values to the columnTypes variable.

    columnTypes, err := rows.ColumnTypes()

    By traversing the columnTypes list, the application code can determine the types of returned columns.

    The type ColumnType variable provides APIs to describe the column types available in database tables.

    Table 1 Common methods for using the APIs provided by type ColumnType

    Method

    Description

    Return Type

    (ci *ColumnType)DatabaseTypeName()

    Returns a column-type database system name. If an empty string is returned, that type of name is not supported.

    Error

    (ci *ColumnType)DecimalSize()

    Returns the scale and precision of the decimal type. If the value of ok is false, the specified type is unavailable or unsupported.

    Precision and scale: int64; ok: Boolean

    (ci *ColumnType)Length()

    Returns the length of a data column type. If the value of ok is false, the specified type does not have a variable length.

    Length: int64; ok: Boolean

    (ci *ColumnType)ScanType()

    Returns a Go type that can be used for Rows.scan.

    reflect.Type

    (ci *ColumnType)Name()

    Returns the name of a data column.

    String

  10. Close the connection using the database connection object created in 2.

    The database connection object provides the Close API for closing the database connection.

    func (db *DB) Close() error

    Execute the following statement to close the database connection object created in 2:

    db.Close()