Build a Go application

2023-09-06 07:12:37  Updated

This topic describes how to build a Go application with OceanBase Database and Go MySQL Driver.

Prerequisites

You have deployed a Go environment on your computer.

Procedure

Step 1: Obtain a database connection string

Obtain a database connection string from a database deployment engineer or administrator. For example:

obclient  -h100.88.xx.xx -uroot@test -p****** -P2881 -Doceanbase

The database connection string contains parameters required for accessing OceanBase Database. Before you create an application, you can log on to OceanBase Database by using the database connection string, to verify that the parameters are correct.

The parameters are described as follows:

  • -h: the IP address for connecting to OceanBase Database, which is sometimes the IP address of an OceanBase Database Proxy (ODP).
  • -u: the username for connecting to a tenant, in the format of username@tenant name#cluster name. The default tenant of a cluster is sys, and the default administrator of a tenant is root. The cluster name is not required when you directly connect to OceanBase Database, but is required when you connect to OceanBase Database through an ODP.
  • -p: the user password.
  • -P: the port for connecting to OceanBase Database, which is also the listening port of the ODP.
  • -D: the name of the database to be accessed.

Step 2: Install Go MySQL Driver

You can install Go MySQL Driver by using different methods based on the version of the Go language.

Use the go get command to install Go MySQL Driver

If you use Go 1.13 to 1.16, you can run the following command to install Go MySQL Driver:

go get -u github.com/go-sql-driver/mysql

For more information about Go MySQL Driver, see GitHub.

Use the go install command to install Go MySQL Driver

If you cannot use the go get command due to the version or network issues, you can perform the following steps to install Go MySQL Driver:

  1. Clone the Go MySQL Driver repository from GitHub to the go/src directory.

    cd /usr/local/go/src   
    git clone https://github.com/go-sql-driver/mysql.git
    

    Notice

    You must replace /usr/local/go/src with the installation directory of the Go language.

  2. Run the go install command.

    go install mysql
    

    Notice

    For some Go versions, the go install command cannot be executed in the /src directory. You can identify the correct directory based on the error reported after you run the go install command. For example, if the following error is reported: cannot find package "mysql" in: /usr/local/go/src/vendor/mysql, you must put the mysql folder in the /src/vendor directory and then run the go install command.

Step 3: Write an application

The following test.go sample file is for your reference:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "mysql"
    // Specify the installation path of Go MySQL Driver. If it is installed in the /src directory, you can specify "mysql" as the path.
)

type Str struct {
    Name       string
}

func main() {
    select_all()
    }

func select_all() {
    conn := "root:@tcp(127.0.0.1:2881)/test"
    db, err := sql.Open("mysql", conn)
    if err != nil {
        log.Fatal(err)
    }

    defer db.Close()

    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("success to connect OceanBase with go_mysql driver\n")
    // Create a table named t1.
    db.Query("create table t1(str varchar(256))")
    // Insert data.
    db.Query("insert into  t1 values ('Hello OceanBase')")
    // Query data.
    res, err := db.Query("SELECT * FROM t1")
    // Drop the t1 table.
    db.Query("drop table t1")
    if err != nil {
        log.Fatal(err)
    }

    defer res.Close()

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

    for res.Next() {

        var str Str
        res.Scan(&str.Name)
        fmt.Printf("%s\n", str.Name)
    }
}

Modify the database connection parameters in the code. The parameters are concatenated, and the values of the parameters are from the database connection string obtained in Step 1.

// Format
conn := "{username}:{password}@tcp({hostname}:{port})/{dbname}"
// Example
conn := "root:@tcp(127.0.0.1:2881)/test"

The parameters are described as follows:

  • username: the username for connecting to a tenant, in the format of username@tenant name#cluster name. The value of this parameter is obtained from the -u parameter. The default tenant of a cluster is sys, and the default administrator of a tenant is root. The cluster name is not required when you directly connect to OceanBase Database, but is required when you connect to OceanBase Database through an ODP.

  • password: the user password. The value of this parameter is obtained from the -p parameter.

  • hostname: the IP address for connecting to OceanBase Database, which is sometimes the IP address of an ODP. The value of this parameter is obtained from the -h parameter.

  • port: the port for connecting to OceanBase Database, which is also the listening port of the ODP. The value of this parameter is obtained from the -P parameter.

  • dbname: the name of the database to be accessed. The value of this parameter is obtained from the -D parameter.

Step 4: Run the application

After you edit the code, run the following command:

// Configure temporary environment variables based on the installation path of the Go language.
export PATH=$PATH:/usr/local/go/bin

// Execute the sample script.
go run test.go

// Alternatively, generate a binary file and then run it.
go build test.go
./test

If the following results are returned, you have connected to OceanBase Database, and the sample script is correctly executed.

success to connect OceanBase with go_mysql driver
Hello OceanBase

Contact Us