In a previous post, I demonstrated how to connect to an IBM Db2 database using PHP. However, PHP isn’t the only language with a native driver for IBM Db2. Another popular language with an IBM Db2 driver is Go…and coincidentally, that’s also the topic of this post.

Install the IBM Db2 driver in your Go module as below:

go get github.com/ibmdb/go_ibm_db

As with other databases, you use the IBM Db2 driver for Go via the Go sql package, which provides a generic abstraction layer for database operations. Here’s an example:

package main

import (
  "database/sql"
  "fmt"
  "log"

  _ "github.com/ibmdb/go_ibm_db"
)

type Book struct {
  Id    string `db:"ID"`
  Title string `db:"TITLE"`
}

func main() {
  dsn := "HOSTNAME=localhost;DATABASE=library;PORT=50000;UID=user;PWD=password"
  db, err := sql.Open("go_ibm_db", dsn)
  if err != nil {
    log.Fatalln(err)
  }
  st, err := db.Prepare("SELECT ID, TITLE FROM BOOKS")
  if err != nil {
    log.Fatalln(err)
  }
  rows, err := st.Query()
  if err != nil {
    log.Fatalln(err)
  }
  defer rows.Close()

  for rows.Next() {
    b := Book{}
    err = rows.Scan(&b.Id, &b.Title)
    if err != nil {
      log.Fatalln(err)
    }
    fmt.Println(b.Id, b.Title)
  }
}

This listing defines a new Book struct, representing a record from the database. The struct has two fields, one for the book identifier and the other for the book title.

The sql.Open() method opens a connection to the database server, passing it a DSN. Note that you can prepare the DSN manually, as in the example above or, if you’re running on IBM Cloud, you can extract the DSN from the IBM Cloud VCAP_SERVICES or CE_SERVICES environment variables.

Once the connection is made, the Prepare() method prepares a SELECT query and the Query() method executes it. The code loops over the results of the query, converting each record into a Book struct using the Scan() method and printing its fields.

Needless to say, the IBM Db2 driver for Go includes many other methods as well. You can read all about them in the package documentation.