How to Connect Golang with MySQL

Today, I will describe MySQL database connectivity with golang. MySQL is most popular open source relational database. I will let you know step by step how to golang connect with MySQL database.

I assumed you have configured golang environment within your system, if not please configure golang environment into your system.

The golang have MySQL package that help to connect MySQL with golang. We will use that package and configure db connectivity.

We will create following files into this MySQL golang example –

  • main.go : This is main go application entry file and have method.
  • db/db_connection.go : This file will have database connection method and return MySQL connection object.

Simple Golang MySQL example

We will create 'mysql_example_golang' folder under my golang work path D:\go-work.Let’s create main.go file into this folder D:\go-work\mysql_example_golang\main.go.

I have created 'test' database into MySQL database server with db username and password.We will use this information later on into this tutorial.

Golang MySQL MySQL Package

There are a couple of drivers available to support MySQL in Go. We will use which have implemented the database/sql interface.

We will create db_connection.go file for database connection into db folder.We will use base SQL package 'database/sql' with MySQL driver.Let’s add below code into db_connection.go file.

As shown above file, We have passed username:root, hostname:localhost, port:3306 and dbname:test. You need to change as per you MySQL database details.

We are creating MySQL database connection using open() method, Now we are checking open() method return error or db object, if db object then print message into console ‘MySQL db is connected’.

How To Use MySQL Connection Object into Golang APP

We have created MySQL db connect and will use into golang main.go file, we will import ‘db’ package into main app file and use CreateCon() method.

As you can see, I have create a con variable which is DB type, since CreateCon() method return DB type variable.

How to Run Golang Application

Now, cd to the location of main.go file D:\go-work\mysql_example_golang\ and run below command to run go program.
$ go get
$ go run main.go

The go get command will download third party package libs into your work-space, here is – mysql driver package.

if every thing fine, then you will get “MySQL db is connected” message into console.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.