Connecting to MatrixOne with Golang
MatrixOne supports Golang application connection, Go-MySQL-Driver is supported. This tutorial will walk you through how to connect MatrixOne with Golang.
Before you start
- Make sure you have already installed and launched MatrixOne.
- Make sure you have already installed Golang 1.18 and plus.
1. #To check with Golang installation and its version
2. go version
- Make sure you have already installed MySQL client.
Using Golang to connect to MatrixOne
Go-MySQL-Driver is a MySQL driver for Go’s (golang) database/sql package.
- Install
go-mysql-drivertool. Simple install the package to your $GOPATH with the go tool from shell. Make sure Git is installed on your machine and in your system’sPATH.
1. > go get -u github.com/go-sql-driver/mysql
2. Connect to MatrixOne by MySQL client. Create a new database named test.
1. mysql> create database test;
3. Create a plain text file golang_connect_matrixone.go and put the code below.
``` 1. package main
- import (
- "database/sql"
- "fmt"
- _ "github.com/go-sql-driver/mysql"
-
)
-
func main() {
- //"username:password@protocol/database"
- db, _ := sql.Open("mysql", "dump:111@tcp(127.0.0.1:6001)/test") // Set database connection
- defer db.Close() //Close DB
- err := db.Ping() //Connect to DB
- if err != nil {
- fmt.Println("Database Connection Failed") //Connection failed
- return
- } else {
- fmt.Println("Database Connection Succeed") //Connection succeed
- }
- } ```
- Execute this golang file in the command line terminal.
1. > go run golang_connect_matrixone.go
2. Database Connection Succeed
Reference
For the example about using Golang to build a simple CRUD with MatrixOne, see Build a simple Golang CRUD demo with MatrixOne.
