Chapter 4.
Database-driven responses
For our Snippetbox web application to become truly useful we need somewhere to store (or persist) the data entered by users, and the ability to query this data store dynamically at runtime.
There are many different data stores we could use for our application — each with different pros and cons — but we’ll opt for the popular relational database MySQL.
In this section you’ll learn how to:
- Install a database driver to act as a ‘middleman’ between MySQL and your Go application.
- Connect to MySQL from your web application (specifically, you’ll learn how to establish a pool of reusable connections).
- Create a standalone
models
package, so that your database logic is reusable and decoupled from your web application. - Use the appropriate functions in Go’s
database/sql
package to execute different types of SQL statements, and how to avoid common errors that can lead to your server running out of resources. - Prevent SQL injection attacks by correctly using placeholder parameters.
- Use transactions, so that you can execute multiple SQL statements in one atomic action.