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