This topic describes how to use Go-MySQL-Driver and OceanBase Database to build an application that performs basic database operations such as creating tables, inserting data, and querying data.
Download the go-oceanbase sample project
Prerequisites
You have completed the following preparations and correctly configured the corresponding environment variable:
Install OceanBase Database
Install Go
Install Go-MySQL-Driver
Procedure
The steps provided in this topic are for Windows environments. If you are using a different operating system or compiler, the steps may vary slightly.
(Optional) Install Go and Go-MySQL-Driver.
Obtain the connection information of OceanBase Database.
Modify the database connection information in the
go-oceanbaseproject.Run the
go-oceanbaseproject.
Step 1: (Optional) Install Go and Go-MySQL-Driver
If you have installed Go and Go-MySQL-Driver, skip this step. If not, perform the following operations:
Install Go.
Download the Go installation package that suits your operating system from the Go official website.
NoteThe installation package used in this topic is go1.20.6.windows-amd64.msi.
Double-click the installation package and follow the wizard to install Go.
Add the installation path of Go to the Path environment variable of the system.
In a Windows environment, choose Control Panel > System and Security > System > Advanced system settings > Environment Variables > System variables and add
C:\usr\local\go\binto the value of Path.In a Linux or macOS environment, add the following content in the
~/.bashrcor~/.bash_profilefile:export PATH=$PATH:/usr/local/go/bin
NoteHere,
\usr\local\go\binis the default installation directory of Go. If you select another directory when you install Go, replace the default directory with the actual one.Run the following command in a command-line terminal to check the version of Go, thus verifying the installation:
C:\Users\admin\> go version go version go1.20.6 windows/amd64
Install Go-MySQL-Driver.
You can install Go-MySQL-Driver by using different methods based on the version of Go. To install Go-MySQL-Driver, you must open a command-line terminal in the project directory. For more information about Go-MySQL-Driver, see
go-sql-driver/mysqlon GitHub.The installation commands are as follows:
C:\Users\admin\Desktop\go-oceanbase>go get -u github.com/go-sql-driver/mysql go: downloading github.com/go-sql-driver/mysql v1.7.1 go: added github.com/go-sql-driver/mysql v1.7.1If you cannot use the
go getcommand due to version or network issues, you can run thego installcommand to installgo-sql-driver/mysql.Clone the
go-sql-driver/mysqlrepository from GitHub to thego/srcdirectory.cd /usr/local/go/src git clone https://github.com/go-sql-driver/mysql.gitImportantYou must replace
/usr/local/go/srcwith the actual installation directory of Go.Run the
go installcommand.go install mysqlImportantFor some Go versions, the default running directory for the
go installcommand may not be/src. You can determine the correct directory based on the error reported after you run thego installcommand. For example, if thecannot find package "mysql" in: /usr/local/go/src/vendor/mysqlerror is reported, you must put the mysql folder in the/src/vendordirectory and then run the command again.Check whether Go-MySQL-Driver has been installed. If the installation fails, make corrections based on the error message.
go list -m github.com/go-sql-driver/mysql
Step 2: Obtain the connection information of OceanBase Database
Contact a deployment engineer or administrator of OceanBase Database to obtain the database connection string.
obclient -h{host} -u{username} -p****** -P{port} -D{schema_name}
The database connection string contains parameters required for accessing OceanBase Database. You can log in to OceanBase Database by using the database connection string, to verify that the parameters are correct.
The URL obtained here is required in the test.go file.
The parameters are described as follows:
host: the IP address for connecting to OceanBase Database.user_name: the username of the tenant account.password: the password of the tenant account.port: the port for connecting to OceanBase Database. The default port is 3306.schema_name: the name of the schema to access.
Step 3: Modify the database connection information in the go-oceanbase project
Modify the database connection information in the test.go file based on the information obtained in Step 2: Obtain the connection information of OceanBase Database. Select and right-click the test.go file, choose Open With, and select Notepad or another editor to open the file.
Here is an example:
The IP address of the OBServer node is
xxx.xxx.xxx.xxx.The port is 3306.
The name of the schema to access is
test.The username of the tenant account is
root.The password of the tenant account is
******.
The sample connection string is as follows:
conn := "root:******@tcp(xxx.xxx.xxx.xxx:3306)/test"
Step 4: Run the go-oceanbase project
After you modify the code as needed, open a command-line terminal in the project directory and enter the go run command to run the Go file.
C:\Users\admin\Desktop\go-oceanbase>go run test.go
(Optional) In a Linux or macOS environment, you must configure a temporary environment variable before you can run go run.
export PATH=$PATH:/usr/local/go/bin
go run test.go
If the following information is returned, you have connected to OceanBase Database, and the sample project runs properly.
This result is returned for the execution where code for dropping the table t1 is commented out.
C:\Users\admin\Desktop\go-oceanbase>go run test.go
success to connect OceanBase with go_mysql driver
Hello OceanBase
Project code introduction
Click go-oceanbase to download the project code, which is a compressed file named go-oceanbase.
After decompressing it, you will find a folder named go-oceanbase. The directory structure is as follows:
|-- go.mod
|-- go.sum
|-- test.go
Here is a breakdown of the files and directories:
go.mod: the Go module file that defines the dependencies of the project on other modules and versions of the modules.go.sum: the module management file for Go 1.11 and later. It records the dependencies of the project on other modules and versions of the modules, as well as the corresponding checksums.test.go: the Go source code file that contains sample code for the project.
Code in go.mod
The go.mod file defines the module name, Go version, and dependencies of the project.
Code in the go.mod file contains the following parts:
module go-oceanbase: the name of the module, which defines the project namespace. In Go 1.16 and later, the module name must match the name of the root directory of the project.go 1.20: the Go version required for the project.require github.com/go-sql-driver/mysql v1.7.1 // indirect: the dependency declaration of the project. It declares that the project depends on thegithub.com/go-sql-driver/mysqlmodule of version 1.7.1, and that the dependency is an indirect dependency associated with thego.sumdependency.
Code in go.sum
The go.sum file defines the version of the github.com/go-sql-driver/mysql dependency to ensure that the project uses the correct version.
Code in the go.sum file contains the following parts:
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=: provides the hash value of the source code file of the module, which ensures that the correct version is used when the project is built. The hash value here islUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=.github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=: provides the hash value of the dependency file of the module, which ensures that the correct dependency version is used when the project is built. The hash value here isOXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=.
Code in test.go
The test.go file defines how to use Go to interact with the MySQL mode of OceanBase Database, including operations such as connecting to the database, creating tables, inserting data, querying data, and dropping tables. To configure the test.go file, perform the following steps:
Define the
mainpackage.package mainindicates that this package is an executable program package that contains amain()function. The function is executed when the program runs.Define
importpackages.The
importstatement imports the following four packages:database/sql: provides common SQL database access interfaces. It defines a set of common interfaces and functions for connecting to and operating various types of SQL databases.fmt: provides functions to format the input and output. It defines a set of functions for formatting data into strings and outputting them to the console or other devices.log: provides logging functions. It defines a set of functions for outputting logs to the console or other devices.github.com/go-sql-driver/mysql: provides the driver in MySQL mode. It implements the interfaces defined in thedatabase/sqlpackage for connecting to and operating the MySQL mode of OceanBase Database by using Go. You need to specify the correct installation path ofgo-sql-driver/mysqlhere.
The sample code is as follows:
import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" // Specify the installation path of go-sql-driver/mysql. )Define the
Strstruct. The struct contains theNamefield for storing query results. In the struct, define themain()function, which contains theselectAll()function for creating tables, inserting data, querying data, and dropping tables.The sample code is as follows:
type Str struct { Name string } func main() { selectAll() }Define the
selectAll()function.The
selectAll()function includes operations of connecting to the database, creating tables, inserting data, querying data, and dropping tables.Connect to the database. Define the connection string
conn, which contains the connection parameters for the MySQL mode of OceanBase Database, including the username, password, IP address, port number, and database name. Call thesql.Open()function to open the database connection. If an error occurs, log the error and exit the program. Use thedeferkeyword to defer the closure of the database connection, which ensures that the connection is closed after the function is executed.The sample code is as follows:
conn := "user_name:******@tcp(host:port)/schema_name" // Database connection parameters db, err := sql.Open("mysql", conn) if err != nil { log.Fatal(err) }Print messages to the console. Use the
deferkeyword to defer the execution of thedb.Close()function, which ensures that the database connection is closed after the function is executed. Use thefmt.Printf()function to output a successful connection message to the console.The sample code is as follows:
defer db.Close() if err != nil { log.Fatal(err) } fmt.Printf("success to connect OceanBase with go_mysql driver\n")Create a table. Create a table named
t1that contains thestrfield of thevarchar(256)type.The sample code is as follows:
_, err = db.Query("create table t1(str varchar(256))") if err != nil { log.Fatal(err) }Insert data. Insert a row where
strisHello OceanBaseinto thet1table.The sample code is as follows:
_, err = db.Query("insert into t1 values ('Hello OceanBase')") if err != nil { log.Fatal(err) }Query data. Query all data in the
t1table and assign the query result to the variableres. Return an error message if the query fails.The sample code is as follows:
res, err := db.Query("SELECT * FROM t1") if err != nil { log.Fatal(err) } defer res.Close() for res.Next() { var str Str res.Scan(&str.Name) fmt.Printf("%s\n", str.Name) }Drop a table. Drop the
t1table. Return an error message if the operation fails.The sample code is as follows:
_, err = db.Query("drop table t1") if err != nil { log.Fatal(err) }
Complete code examples
go.mod
module go-oceanbase
go 1.20
require github.com/go-sql-driver/mysql v1.7.1 // indirect
go.sum
github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
test.go
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
// Specify the installation path of go-sql-driver/mysql.
)
type Str struct {
Name string
}
func main() {
selectAll()
}
func selectAll() {
conn := "user_name:******@tcp(host:port)/schema_name"
// Set the database connection parameters.
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.
_, err = db.Query("create table t1(str varchar(256))")
if err != nil {
log.Fatal(err)
}
// Insert data.
_, err = db.Query("insert into t1 values ('Hello OceanBase')")
if err != nil {
log.Fatal(err)
}
// Query data.
res, err := db.Query("SELECT * FROM t1")
if err != nil {
log.Fatal(err)
}
defer res.Close()
for res.Next() {
var str Str
res.Scan(&str.Name)
fmt.Printf("%s\n", str.Name)
}
// Drop the t1 table.
_, err = db.Query("drop table t1")
if err != nil {
log.Fatal(err)
}
}
References
For more information about Go-MySQL-Driver, see go-sql-driver/mysql on GitHub.