Connecting to a Database with Go

Have you ever wondered how you can interact with a database in Go using the Model pattern? Well here’s a quick example of how you can get started with GORM, an ORM for Go.

In this example we connect to an SQLite database called database.db and migrate a new table for users. We then add a new user row with the name “Craig” and fetch all users. We finish by printing out the JSON representation of this list of users.

GORM makes interacting with databases in Go dead simple and is just one of the many tools you can use to encapsulate your data layer in the Model architecture.

Check it out here.

Before running this, please ensure the environment you’re running this on has SQLite and that you’ve run the following go get commands:

go get github.com/jinzhu/gorm & go get github.com/jinzhu/gorm/dialects/sqlite

Multi-pronged web developer with a passion for cutting edge tooling! https://craigchilds.dev

Multi-pronged web developer with a passion for cutting edge tooling! https://craigchilds.dev