This topic describes how to use Go to connect to an AnalyticDB for MySQL cluster.

Prerequisites

  • Go tools are downloaded and installed. For more information, visit Getting Started.
  • Go MySQL Driver is installed.
    1. Click here to download Go MySQL Driver.
    2. Use the go tool in shell to install the package to your $GOPATH.
      go get github.com/go-sql-driver/mysql
      Note Make sure that Git is installed on your host and in the PATH environment variable of your system.

Connect to AnalyticDB for MySQL

package main
import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)
const (
   // user: the account used to connect to the AnalyticDB for MySQL cluster. There are two types of accounts: privileged and standard.
    user = "xxx"
    // password: the password of the account used to connect to the AnalyticDB for MySQL cluster.
    password = "xxx"
    // host: the endpoint of the AnalyticDB for MySQL cluster to which you want to connect. You can obtain the endpoint on the Cluster Information page of the AnalyticDB for MySQL console.
    host = "127.0.0.1"
    // 3306: the port number of the AnalyticDB for MySQL cluster endpoint. The default port number is 3306.
    port = 3306
    // database: the name of the database in the AnalyticDB for MySQL cluster.
    database = "database_name"
    // connectTimeout: the timeout period of the database connection.
    connectTimeout = "10s"
)
func main() {
    // Enable the database connection.
    url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s? timeout=%s", user, password, host, port, database, connectTimeout)
    db, err := sql.Open("mysql", url)
    if err ! = nil {
        panic(err.Error())
    }
    // Set the maximum number of enabled connections. The default value is 0, indicating that there is no limit.
    db.SetMaxOpenConns(2)
    // Set the maximum number of idle connections.
    db.SetMaxIdleConns(1)
    // Set the maximum duration of connections. By default, there is no limit on the duration of connections, and connections always keep alive.
    // Connections in the connection pool may be interrupted within one hour.
    // This is not the idle connection timeout period. The connection does not become idle but expires one hour after it is created for the first time.
    // Theoretically, the shorter the maximum duration of the connection, the more frequently connections are created from scratch.
    db.SetConnMaxLifetime(time.Hour)
    // defer the close till after the main function has finished
    // executing
    defer db.Close()
    rows, err := db.Query("show tables")
    if err ! = nil {
        panic(err.Error())
    }
    for rows.Next() {
        var tableName string
        err := rows.Scan(&tableName)
        if err ! = nil {
            panic(err.Error())
        }
        fmt.Println(tableName)
    }
}

Enable Prepared Statement for a server

package main
import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "time"
)
const (
   // user: the account used to connect to the AnalyticDB for MySQL cluster. There are two types of accounts: privileged and standard.
    user = "xxx"
    // password: the password of the account used to connect to the AnalyticDB for MySQL cluster.
    password = "xxx"
    // host: the endpoint of the AnalyticDB for MySQL cluster to which you want to connect. You can obtain the endpoint on the Cluster Information page of the AnalyticDB for MySQL console.
    host = "127.0.0.1"
    // 3306: the port number of the AnalyticDB for MySQL cluster endpoint. The default port number is 3306.
    port = 3306
    // database: the name of the database in the AnalyticDB for MySQL cluster.
    database = "xxx"
    // connectTimeout: the timeout period of the database connection.
    connectTimeout = "10s"
)
func main() {
    // open the database connection
    url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s? timeout=%s", user, password, host, port, database, connectTimeout)
    db, err := sql.Open("mysql", url)
    if err ! = nil {
        panic(err.Error())
    }
    // Set the maximum number of enabled connections. The default value is 0, indicating that there is no limit.
    db.SetMaxOpenConns(2)
    // Set the maximum number of idle connections.
    db.SetMaxIdleConns(1)
    // Set the maximum duration of connections. By default, there is no limit on the duration of connections, and connections always keep alive.
    // Connections in the connection pool may be interrupted within one hour.
    // This is not the idle connection timeout period. The connection does not become idle but expires one hour after it is created for the first time.
    // Theoretically, the shorter the maximum duration of the connection, the more frequently connections are created from scratch.
    db.SetConnMaxLifetime(time.Hour)
    defer db.Close()
    stmt, err := db.Prepare("select * from student where id = ?")
    if err ! = nil {
        panic(err.Error())
    }
    defer stmt.Close()
    rows, err := stmt.Query(9)
    if err ! = nil {
        panic(err.Error())
    }
    defer rows.Close()
    for rows.Next() {
        var id string
        var name string
        var unit string
        err := rows.Scan(&id, &name, &unit)
        if err ! = nil {
            panic(err.Error())
        }
        fmt.Println(fmt.Sprintf("%s, %s, %s", id, name, unit))
    }
}

Enable PrepareStatement for a client

The following example shows that you must set interpolateParams to true to enable PrepareStatement for Go MySQL Driver:

package main
import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "time"
)
const (
    // user: the account used to connect to the AnalyticDB for MySQL cluster. There are two types of accounts: privileged and standard.
    user = "xxx"
    // password: the password of the account used to connect to the AnalyticDB for MySQL cluster.
    password = "xxx"
    // host: the endpoint of the AnalyticDB for MySQL cluster to which you want to connect. You can obtain the endpoint on the Cluster Information page of the AnalyticDB for MySQL console.
    host = "127.0.0.1"
    // 3306: the port number of the AnalyticDB for MySQL cluster endpoint. The default port number is 3306.
    port = 3306
    // database: the name of the database in the AnalyticDB for MySQL cluster.
    database = "xxx"
    // connectTimeout: the timeout period of the database connection.
    connectTimeout = "10s"
)
func main() {
    // Enable the database connection.
    url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s? timeout=%s&interpolateParams=true", user, password, host, port, database, connectTimeout)
    db, err := sql.Open("mysql", url)
    if err ! = nil {
        panic(err.Error())
    }
    // Set the maximum number of enabled connections. The default value is 0, indicating that there is no limit.
    db.SetMaxOpenConns(2)
    // Set the maximum number of idle connections.
    db.SetMaxIdleConns(1)
    // Set the maximum duration of connections. By default, there is no limit on the duration of connections, and connections always keep alive.
    // Connections in the connection pool may be interrupted within one hour.
    // This is not the idle connection timeout period. The connection does not become idle but expires one hour after it is created for the first time.
    // Theoretically, the shorter the maximum duration of the connection, the more frequently connections are created from scratch.
    db.SetConnMaxLifetime(time.Hour)
    defer db.Close()
    rows, err := db.Query("select * from student where id = ?", 9)
    if err ! = nil {
        panic(err.Error())
    }
    defer rows.Close()
    for rows.Next() {
        var id string
        var name string
        var unit string
        err := rows.Scan(&id, &name, &unit)
        if err ! = nil {
            panic(err.Error())
        }
        fmt.Println(fmt.Sprintf("%s, %s, %s", id, name, unit))
    }
}