MySQL has a massive community around it, and it’s quite possibly powering half the web as the main database technology for WordPress.
It’s incredibly easy to spin up a MySQL instance locally, and thus it’s perfect for building some decent applications on top of.
If you’re new to Go, I recommend you check out this beginner tutorial:The Ultimate Go Guide in 2020 for Beginners.
Go is an open-source programming language that makes it easy to build simple, reliable, and efficient software. In this…levelup.gitconnected.com
Requirements
- You will need Go version 1.11+ installed on your development machine.
Getting Started
To do this, we’ll be using https://github.com/go-sql-driver/mysql as our MySQL driver. Go-SQL-Driver
are a lightweight and fast MySQL driver that supports connections over TCP/IPv4
, TCP/IPv6
, Unix domain sockets
Or custom protocols and features automatic handling of broken connections.
Let’s create a new project:
package main
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/test")
if err != nil {
panic(err.Error())
}
defer db.Close()
}
In the import
section, we import the MySQL driver from Github. In the main
func
we see a new variable is created called db
and err
which gets initialized by opening a database connection.
Arguments help to determine to which database will be connected, the database type is mysql
You can enter your username and password and even your IP and port. After the /
name of the database is put.
Once an error occurs, it will be logged, and if the task completed successfully, the connection would be closed with defer db.Close()
.
Basic SQL Commands
Now that we’ve created a connection, we need to start submitting queries to the database.
db.Query(sql)
It allows us to perform any SQL command we so desire. We can simply construct the query string and pass it in as a parameter.
insert, err := db.Query("INSERT INTO test VALUES ( 2, 'TEST' )")
// if there is an error inserting, handle it
if err != nil {
panic(err.Error())
}
// be careful deferring Queries if you are using transactions
defer insert.Close()
Isn’t that easy? If you want to know more about MySQL, I recommend you visiting this tutorial:The Ultimate SQL Guide for Beginners in 2020.
SQL is a standard language for storing, manipulating, and retrieving data in databases. In this article, I’ll teach you…levelup.gitconnected.com
Filling Structs from Results
Retrieving a set of results from the database is all well and good, but we need to be able to read these results or populating existing structs
so that we can parse them and modify them easily.
To parse several rows, we can use the .Scan(args...)
the method which takes in any number of arguments and allows us to populate a composite object.
An example of a very simple struct
:
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
To fill it with results:
for results.Next() {
var user User
err = results.Scan(&user.ID, &user.Name)
if err != nil {
panic(err.Error())
}
log.Printf(user.Name)
}
With this simple for loop, we’ll loop through the results and create a user
variable of the type User
. After that an err
the variable gets initialized by scanning through the results and putting them in that user
variable.
Now you can use that data and manipulate it, or view it, display it or do anything you like.
Conclusion
In this tutorial, we managed to set up a connection to a MySQL and then perform some simple queries to that database and marshal the returned responses into a struct
or an array of structs
. This should hopefully give you everything you need to take things further and build your own Go applications on top of MySQL.