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

  1. Make sure you have already installed and launched MatrixOne.
  2. Make sure you have already installed Golang 1.18 and plus.
  1. #To check with Golang installation and its version
  2. go version
  1. 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.

  1. Install go-mysql-driver tool. 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’s PATH.

    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
    2. import (
    3. "database/sql"
    4. "fmt"
    5. _ "github.com/go-sql-driver/mysql"
    6. )
    7. func main() {
    8. //"username:password@[protocol](address:port)/database"
    9. db, _ := sql.Open("mysql", "dump:111@tcp(127.0.0.1:6001)/test") // Set database connection
    10. defer db.Close() //Close DB
    11. err := db.Ping() //Connect to DB
    12. if err != nil {
    13. fmt.Println("Database Connection Failed") //Connection failed
    14. return
    15. } else {
    16. fmt.Println("Database Connection Succeed") //Connection succeed
    17. }
    18. }
  4. 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.