Build a Go application

The following tutorial creates a simple Go application that connects to a YugabyteDB cluster using the Go PostgreSQL driver, performs a few basic database operations — creating a table, inserting data, and running a SQL query — and then prints the results to the screen.

Before you begin

This tutorial assumes that you have satisfied the following prerequisites.

YugabyteDB

YugabyteDB is up and running. If not, please follow these steps in the Quick Start guide.

Go

Go version 1.8, or later, is installed.

Go PostgreSQL driver

The Go PostgreSQL driver package (pq) is a Go PostgreSQL driver for the database/sql package.

To install the package locally, run the following command:

  1. $ go get github.com/lib/pq

Create the application

Create a file ybsql_hello_world.go and copy the contents below.

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. _ "github.com/lib/pq"
  7. )
  8. const (
  9. host = "127.0.0.1"
  10. port = 5433
  11. user = "yugabyte"
  12. password = "yugabyte"
  13. dbname = "yugabyte"
  14. )
  15. func main() {
  16. psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
  17. "password=%s dbname=%s sslmode=disable",
  18. host, port, user, password, dbname)
  19. db, err := sql.Open("postgres", psqlInfo)
  20. if err != nil {
  21. log.Fatal(err)
  22. }
  23. var createStmt = `CREATE TABLE employee (id int PRIMARY KEY,
  24. name varchar,
  25. age int,
  26. language varchar)`;
  27. if _, err := db.Exec(createStmt); err != nil {
  28. log.Fatal(err)
  29. }
  30. fmt.Println("Created table employee")
  31. // Insert into the table.
  32. var insertStmt string = "INSERT INTO employee(id, name, age, language)" +
  33. " VALUES (1, 'John', 35, 'Go')";
  34. if _, err := db.Exec(insertStmt); err != nil {
  35. log.Fatal(err)
  36. }
  37. fmt.Printf("Inserted data: %s\n", insertStmt)
  38. // Read from the table.
  39. var name string
  40. var age int
  41. var language string
  42. rows, err := db.Query(`SELECT name, age, language FROM employee WHERE id = 1`)
  43. if err != nil {
  44. log.Fatal(err)
  45. }
  46. defer rows.Close()
  47. fmt.Printf("Query for id=1 returned: ");
  48. for rows.Next() {
  49. err := rows.Scan(&name, &age, &language)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. fmt.Printf("Row[%s, %d, %s]\n", name, age, language)
  54. }
  55. err = rows.Err()
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. defer db.Close()
  60. }

Run the application

To execute the file, run the following command:

  1. $ go run ybsql_hello_world.go

You should see the following as the output.

  1. Created table employee
  2. Inserted data: INSERT INTO employee(id, name, age, language) VALUES (1, 'John', 35, 'Go')
  3. Query for id=1 returned: Row[John, 35, Go]