Accessing an Oracle DB in Go

Oracle DB

Intro

This week I needed to access an Orable DB from GO and so I embarked on a journey that lasted almost 2 days. Everywhere I looked the documentation on how to get this going was not very intuitive so once I actually got it going, I decided to write my own how-to in order not to forget it.

How-To

  1. Download Client files:
    • instantclient-basic-macos.x64-12.1.0.2.0.zip
    • instantclient-sdk-macos.x64-12.1.0.2.0.zip
    • instantclient-sqlplus-macos.x64-12.1.0.2.0.zip
  2. unzip in one directory say: /Oracle (this will create the /Oracle/instantclient_12_1 directory)
  3. Create the oci8.pc file in the ‘/Oracle/instantclient_12_1’ directory and put this in it:

    prefixdir=/Oracle/instantclient_12_1/sdk
    libdir=${prefixdir}
    includedir=${prefixdir}/include
        
    Name: OCI
    Description: Oracle database driver
    Version: 11.2
    Libs: -L${libdir} -lclntsh
    Cflags: -I${includedir}
    
  4. edit your .bashrc (or .zshrc) and put this in it:

    • PKG_CONFIG_PATH=/Oracle/instantclient_12_1’
    • LD_LIBRARY_PATH=/Oracle/instantclient_12_1’
  5. Symlink the libraries to /usr/lib/

    • ln -s /Oracle/instantclient_12_1/libclntsh.dylib.12.1 /usr/lib/libclntsh.dylib
    • ln -s /Oracle/instantclient_12_1/libocci.dylib.12.1 /usr/lib/libocci.dylib
    • NOTE: if you are using a Mac and you are on El Capitan, you will need to disable ‘rootless’ protection
      • Reboot in recovery mode (Press Cmd-R during the reboot)
      • Start a command line and run the command: ‘csrutil disable’
      • Reboot again
      • Now you can enter the symlinks as above.
  6. run: ‘go get github.com/mattn/go-oci8’

  7. All Set

  8. edit oracle_db.go:

    package main
        
    import (
        "fmt"
        "database/sql"
        _ "github.com/mattn/go-oci8"
    )
        
    func main(){
        db, err := sql.Open("oci8", "username/password@localhost:1521/xe")
        if err != nil {
            fmt.Println(err)
            return
        }
        defer db.Close()
        
        if err = db.Ping(); err != nil {
            fmt.Printf("Error connecting to the database: %s\n", err)
            return
        }
        
        rows,err := db.Query("select 2+2 from dual")
        if err != nil {
            fmt.Println("Error fetching addition")
            fmt.Println(err)
            return
        }
        defer rows.Close()
        
        for rows.Next() {
            var sum int
            rows.Scan(&sum)
            printf("2 + 2 always equals: %d\n", sum)
        }
    }
    
  9. go run oracle_db.go

    • should see printed on the console: ‘2+2 always equals: 4’

In The End

I hope this helps someone else to come to terms with accessing an oracle DB from golang.

Happy GOing!!

*** Sign up for my email list to keep in touch with all the interesting new happenings in the go community with the GolangNewsFeed

comments powered by Disqus