Golang : Connect to database (MySQL/MariaDB) server

Database is the main workhorse powering most dynamic content websites today and yet most of the time a database is hidden from view. Any apps or websites must be able to connect to a database in order to persist/save data and server the data according to different situations.

This tutorial will explore how to connect to MySQL / Maria DB server will Golang and it uses the "github.com/go-sql-driver/mysql" third party package. It also assumes that you already know and have setup a MySQL or MariaDB database.

These codes will demonstrate how to connect to a database server and retrieve some data with a select statement.

 package main

 import (

 // without the underscore _, you will get imported but not
 // used error message
 _ "github.com/go-sql-driver/mysql"

 func main() {
 // connect to our database server with data source name
 // data source name configuration has the following parameters :
 // [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]

 // example config :
 // user:password@tcp(

 conn, err := sql.Open("mysql", "db_username:db_password@protocol(address:port_num)/database_name")
 if err != nil {

 // use your own select statement
 // this is just an example statement
 statement, err := conn.Prepare("select title from posts limit 10") 

 if err != nil {

 rows, err := statement.Query() // execute our select statement

 if err != nil {

 for rows.Next() {
 var title string
 fmt.Println("Title of tutorial is :", title)


Output :

> ./connectmysql

Title of tutorial is : A tutorial for Go's database/sql package

Title of tutorial is : Check CentOS version

Title of tutorial is : CodeIgniter : Import Linkedin data

Title of tutorial is : CodeIgniter : Load different view for mobile devices

Title of tutorial is : Convert JSON to CSV in Golang

Title of tutorial is : Create directory in Go

Title of tutorial is : Default cipher that OpenSSL used to encrypt a PEM file

Title of tutorial is : Delete a directory in Go

Title of tutorial is : Detect Operating System in Go

Title of tutorial is : Elasticsearch : Shutdown a local node

Hope this short tutorial will help you to learn how to connect to the MySQL/MariaDB database.

References :



By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.