This topic introduces how to build an application by using Go-SQL-Driver/MySQL and OceanBase Database. It also covers the use of the application for fundamental database operations, including table creation, data insertion, and data query.
Prerequisites
You have completed the following preparations and correctly configured the corresponding environment variable:
- Install OceanBase Database
- Install Go
- Install Go-SQL-Driver/MySQL
Procedure
Note
The steps outlined in this topic are for the Windows environment. If you are using a different operating system or compiler, the steps may vary slightly.
- (Optional) Install Go and Go-SQL-Driver/MySQL.
- 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-SQL-Driver/MySQL
If you have installed Go and Go-SQL-Driver/MySQL, skip this step. If you have not installed them, perform the following operations:
Install Go.
Download the Go installation package that suits your operating system from the Go official website.
Note
The 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
Pathenvironment 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/binNote
Here,
\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.
Enter the following command in the 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-SQL-Driver/MySQL.
You can install Go-SQL-Driver/MySQL by using different methods based on the version of Go. To install Go-SQL-Driver/MySQL, you must open a command-line terminal in the project directory. For more information about
Go-SQL-Driver/MySQL, see GitHub.The 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 for installation.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.gitNotice
You must replace
/usr/local/go/srcwith the actual installation directory of Go.Run the
go installcommand.go install mysqlNotice
For 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 the following error is reported:cannot find package "mysql" in: /usr/local/go/src/vendor/mysql, you must put themysqlfolder in the/src/vendordirectory and then run thego installcommand.Check whether Go-SQL-Driver/MySQL 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 the deployment personnel 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.
Note
The URL obtained here is required in the test.go file.
Parameters in the connection string are described as follows:
host: the IP address for connecting to OceanBase Database. For connection through OceanBase Database Proxy (ODP), this parameter is the IP address of an ODP. For direct connection, this parameter is the IP address of an OBServer node.user_name: the tenant account. For connection through ODP, the tenant account can be in theusername@tenant name#cluster nameorcluster name:tenant name:usernameformat. For direct connection, the tenant account is in theusername@tenant nameformat.password: the account password.port: the port for connecting to OceanBase Database. For connection through ODP, the default value is2883, which can be customized when ODP is deployed. For direct connection, the default value is2881, which can be customized when OceanBase Database is deployed.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
10.10.10.1. - The port is 2881.
- The name of the schema to access is
test. - The tenant account is
root@mysql.root@mysqlis a user tenant created in MySQL mode of OceanBase Database. - The password is
******.
The sample code is as follows:
conn := "root@mysql:******@tcp(10.10.10.1:2881)/test"
Step 4: Run the go-oceanbase project
After the code is compiled, 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 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.
Note
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 project's dependencies on other modules and versions of the modules.go.sum: the module management file for Go 1.11 and later. It records the project's dependencies 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 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 of Go-SQL-Driver/MySQL here.
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
Strstructure.The structure contains the
Namefield for storing query results. In the structure, 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 the
sql.Open()function to open the database connection. If an error occurs, log the error and exit the program. - Use the
deferkeyword to defer the closure of the database connection, ensuring 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) }- Define the connection string
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 the
fmt.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")- Use the
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
module go-oceanbase
go 1.20
require github.com/go-sql-driver/mysql v1.7.1 // indirect
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=
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"
// 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 table 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 table t1.
_, err = db.Query("drop table t1")
if err != nil {
log.Fatal(err)
}
}
References
For more information about Go-SQL-Driver/MySQL, see Go-SQL-Driver/MySQL.
Download the go-oceanbase sample project