Today I want to tell about my little experience with MySQL (although you can use any other database here) in Go.

The way to work with the database from Go

I found a great way to work with the database from Go and can't wait to share it.

In general, Go has several important things to do in order to make inquiries. For example, database/sql and github.com/go-sql-driver/mysql

A typical example looks like this:

And in order to map the query result into a structure, we will use github.com/jmoiron/sqlx.

SQLX is a set of extensions on top of the database/sql that allow you to make a minimal “ORM” in Go.

For example, we work with such a model

We have a simple database scheme

The connection to the database will look like this

SQLX bunch of methods

Sqlx has a bunch of methods, which start with a Must. MustExec, MustBegin. You have to use them with caution because they throw panic and your application can crash when you do not want it :)

CRUDs will look like this:

That's all. Just in case, the complete code:

Optimize your backend solutions with Mad Devs.

Latest articles here

SOLID: Interface Segregation Principle in Golang.

SOLID: Interface Segregation Principle in Golang

Acronymic SOLID principles were formulated by Robert C. Martin, also known as "Uncle Bob," one of the most influential software developers in the...

GRPC Streams.

Guaranteed Delivery with gRPC Streams

Let's take a look at the minimum requirements for web developers in the 2000s. In the good old days, you could build more or less working website...

Protocol Buffers vs JSON

Protocol Buffers vs JSON

Have you ever wondered how your favorite mobile app delivers lightning-fast updates or how social media platforms handle millions of messages per...

Go to blog