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 (
 "database/sql"
 "fmt"

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

 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(127.0.0.1:3306)/database



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

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


 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

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

 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

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

 conn.Close()
 }

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 :

https://github.com/go-sql-driver/mysql

http://golang.org/pkg/database/sql/





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.


Advertisement