Installing a database driver
To use MySQL from our Go web application we need to install a database driver. This essentially acts as a middleman, translating commands between Go and the MySQL database itself.
You can find a comprehensive list of available drivers on the Go wiki, but for our application we’ll use the popular go-sql-driver/mysql
driver.
To download it, go to your project directory and run the go get
command like so:
$ cd $HOME/code/snippetbox $ go get github.com/go-sql-driver/mysql@v1 go: added filippo.io/edwards25519 v1.1.0 go: added github.com/go-sql-driver/mysql v1.8.1
Notice here that we’re postfixing the package path with @v1
to indicate that we want to download the latest available version of github.com/go-sql-driver/mysql
with the major release number 1.
At the time of writing the latest version is v1.8.1
, but the version you download might be v1.8.2
, v1.9.0
or similar — and that’s OK. Because the go-sql-driver/mysql
package uses semantic versioning for its releases, any v1.x.x
version should be compatible with the rest of the code in this book.
As an aside, if you want to download the latest version, irrespective of version number, you can simply omit the @version
suffix like so:
$ go get github.com/go-sql-driver/mysql
Or if you want to download a specific version of a package, you can use the full version number. For example:
$ go get github.com/go-sql-driver/mysql@v1.0.3