MySQL and Golang

Introduction

I expect you to know the basics of working with databases, this includes setting up a local MySQL database instance as well as knowing the basics of the SQL language.

Creating our project

We start by simply creating a folder for our project and a file called “main.go” inside of it.

mkdir golang-mysql && cd golang-mysql && touch main.go

The database driver

We will use a MySQL driver in order to connect to our database. The reason we do this is because the driver handles a lot of the stuff necessary to communicate with our database.

go get -u github.com/go-sql-driver/mysql

Initial code

Now we will write some initial code as well as import the needed packages.

package mainimport (
"fmt"
"database/sql"
_"github.com/go-sql-driver/mysql"
)
func main() {

}

Accessing our database

To access our database and create a new database object we use this line of code:

db, err := sql.Open("mysql", "<user>:<password>@tcp(127.0.0.1:3306)/<database-name>")
package mainimport (
"database/sql"
_"github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql",
"<user>:<password>@tcp(127.0.0.1:3306)/<database-name>")
if err != nil {
panic(err.Error())
}
defer db.Close()}
db ,err := sql.Open("mysql", "root:@/<database-name>")
go build && ./golang-mysql

Inserting data

In my database I’ve created a table called “posts” with two columns (id and title).

insert, err := db.Query("INSERT INTO posts(title) VALUES('My post')")if err != nil {
panic(err.Error())
}
defer insert.Close()
package mainimport (
"database/sql"
_"github.com/go-sql-driver/mysql"
)
func main() { db, err := sql.Open("mysql", "<user>:<password>@tcp(127.0.0.1:3306)/<database-name>") if err != nil {
panic(err.Error())
}
defer db.Close() insert, err := db.Query("INSERT INTO posts(title) VALUES('My post')") if err != nil {
panic(err.Error())
}
defer insert.Close()}

Getting data

To get and use the data we first need to define a struct.

type Post struct {
ID int
Title string
}
package mainimport (
"fmt"
"database/sql"
_"github.com/go-sql-driver/mysql"
)
type Post struct {
ID int
Title string
}
func main() { db, err := sql.Open("mysql", "<user>:<password>@tcp(127.0.0.1:3306)/<database-name>") if err != nil {
panic(err.Error())
}
defer db.Close()}
posts, err := db.Query("SELECT id, title FROM posts")if err != nil {
panic(err.Error())
}
for posts.Next() {
var post Post
err := posts.Scan(&post.ID, &post.Title)
if err != nil {
panic(err.Error())
}
fmt.Println(post)}
{1 My post}

Thank you for reading!

I hope this helped you understand the basics of working with databases in Golang, I’m planning to write some more advanced articles on this subject, so if you liked this make sure to leave a review and share.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store