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&...¶mN=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 :
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
Tutorials
+13.2k Golang : Verify token from Google Authenticator App
+17.1k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+7.8k Javascript : Put image into Chrome browser's console
+19k Golang : Calculate entire request body length during run time
+16.1k Golang : Loop each day of the current month example
+25.6k Golang : How to write CSV data to file
+39k Golang : How to read CSV file
+29.7k Golang : How to get HTTP request header information?
+18.3k Golang : Logging with logrus
+10.9k How to test Facebook App on localhost ?
+19.1k Golang : Delete item from slice based on index/key position
+8.7k Golang : Random integer with rand.Seed() within a given range