This topic provides a code example on how to connect a Golang application to OceanBase Database.
Install the Golang driver
Use the go get command (for Go V1.13 - V1.16)
Run the following command to install the Golang driver:
go get -u github.com/go-sql-driver/mysql
Note: For details about Go-SQL-Driver/MySQL, see GitHub.
Use the go install command
If the go get command cannot be used due to version or network reasons, you can try the following:
Clone the go-sql-driver/mysql repository in GitHub to the src directory.
cd /usr/local/go/src git clone https://github.com/go-sql-driver/mysql.gitNote: In some versions, the default directory for
go installmay not be /src, so you can determine the actual directory by the error reported aftergo installis executed. For example, if the error iscannot find package "mysql" in: /usr/local/go/src/vendor/mysql, then put the mysql folder in the /src/vendor directory before running the install command.Run the following command to install the Golang driver:
go install mysql
Connect to OceanBase Database
Run the following sample code to connect to OceanBase Database, where you can use username:password@protocol(address)/dbname?param=value to set the connection string.
package main
···
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql" //Fill in the exact path for installing go-sql-driver/mysql. If installed in the src directory, you can fill in "mysql".
)
type City struct {
Id int
Name string
Population int
}
func select_all() {
conn := "root:@tcp(127.0.0.1:2881)/testdb"
db, err := sql.Open("mysql", conn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err != nil {
log.Fatal(err)
}
res, err := db.Query("SELECT * FROM cities")
if err != nil {
log.Fatal(err)
}
defer res.Close()
if err != nil {
log.Fatal(err)
}
for res.Next() {
var city City
err := res.Scan(&city.Id, &city.Name, &city.Population)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", city)
}
}
Troubleshoot the PreparedStatement error
Log on to OceanBase Database as the root user and run the following command:
alter system set _ob_enable_prepared_statement = true;