An Inside Look: Building Database Driven Apps with Go

Posted by Anna Navatsyk on Mar 25, 2015 7:49:00 AM

Have you downloaded our eBook, Building Database Driven Apps with Go? It's the best resource to quickly learn how to connect a database from Go programs.

This excerpt presents a quick introduction to the major functionality of database/sql in the form of a fully functioning Go program.

Your First database/sql Program

Before you begin, ensure you have access to a MySQL database, as we’ll use MySQL for the example. If you don’t have an instance of MySQL that’s appropriate for testing, you can get one in seconds with the MySQL Sandbox utility.

Create a new Go source file, hello_mysql.go, with the following source code (download). You may need to adjust the connection parameters as needed to connect to your testing database. Note also that the example assumes the default test database exists and your user has rights to it:

 building-go-1.png

 building-go-2.png

Run your new Go program with go run hello_mysql.go. It’s safe to run it multiple times. As you do, you should see output like the following as it continues to insert rows into the table:

 building-go-3.png

Congratulations! You’ve written your first program to interact with a MySQL server using Go, and here are a few highlights:

  • You imported database/sql and loaded a driver for MySQL.

  • You created a sql.DB with a call to sql.Open(), passing the driver name and the connection string.

  • You used Exec() to create a table and insert a row, then inspect the results.

  • You used Query() to select the rows from the table, rows.Next() to iterate over them, and rows.Scan() to copy columns from the current row into variables.

  • You used .Close() to clean up resources when you finished with them.

What might surprise you is that the code you’ve just run is not some kind of overly simplified, silly example. It is very similar to the code you’ll use in production systems under high load, including error handling. Much of this code is discussed in further sections of this book, available for download here.

Recent Posts

Posts by Topic

see all