db2cli

package module
v0.0.0-...-c483351 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 19, 2018 License: BSD-3-Clause Imports: 12 Imported by: 0

README

Package db2cli

The C API for DB2 is called CLI and is basically the same interface as ODBC. However, it can be used without configuring ODBC which simplifies usage for DB2-only projects.

This driver is based on code.google.com/p/odbc.

Building

The following cgo environment variables must be set before building this package:

  • CGO_LDFLAGS
  • CGO_CFLAGS

Here is a sample script which sets these variables:

#!/bin/bash

DB2HOME=$HOME/sqllib
export CGO_LDFLAGS=-L$DB2HOME/lib
export CGO_CFLAGS=-I$DB2HOME/include

go build .

Running

On Linux, LD_LIBRARY_PATH probably needs to be set to find the DB2 CLI libraries. Other platforms may have similar requirements.

This sample script demonstrates the bare minimum needed:

#!/bin/bash

DB2HOME=$HOME/sqllib
export LD_LIBRARY_PATH=$DB2HOME/lib

./dbtest -conn 'DATABASE=db; HOSTNAME=dbhost; PORT=40000; PROTOCOL=TCPIP; UID=me; PWD=secret;'

Note

On some DB2 instances (e.g. z/OS) you may have to connect to DB2-Connect which will forward connection requests to DB2. In theses cases you may run into something like:

SQLExecute: {42601} [IBM][CLI Driver][DB2] SQL0104N  An unexpected token " " was found following "". 
Expected tokens may include:  ". <IDENTIFIER> JOIN INNER LEFT RIGHT FULL CROSS , HAVING GROUP".  SQLSTATE=42601

Although not really obvious, this means that a terminator is missing for SQL statements. This may be due to a different parsing approach when DB2-Connect is involved. If you terminate your SQL statements with ';' you should be fine. Most of the times though you will connect directly to DB2 and SQL statements without ';' terminator work.

Sample program

package main

import (
    _ "bitbucket.org/phiggins/db2cli"
    "database/sql"
    "flag"
    "fmt"
    "os"
    "time"
)

var (
    connStr = flag.String("conn", "", "connection string to use")
    repeat  = flag.Uint("repeat", 1, "number of times to repeat query")
)

func usage() {
    fmt.Fprintf(os.Stderr, `usage: %s [options]

%s connects to DB2 and executes a simple SQL statement a configurable
number of times.

Here is a sample connection string:

DATABASE=MYDBNAME; HOSTNAME=localhost; PORT=60000; PROTOCOL=TCPIP; UID=username; PWD=password;
`, os.Args[0], os.Args[0])
    flag.PrintDefaults()
    os.Exit(1)
}

func execQuery(st *sql.Stmt) error {
    rows, err := st.Query()
    if err != nil {
        return err
    }
    defer rows.Close()
    for rows.Next() {
        var t time.Time
        err = rows.Scan(&t)
        if err != nil {
            return err
        }
        fmt.Printf("Time: %v\n", t)
    }
    return rows.Err()
}

func dbOperations() error {
    db, err := sql.Open("db2-cli", *connStr)
    if err != nil {
        return err
    }
    defer db.Close()
    // Attention: If you have to go through DB2-Connect you have to terminate SQL-statements with ';'
    st, err := db.Prepare("select current timestamp from sysibm.sysdummy1;")
    if err != nil {
        return err
    }
    defer st.Close()

    for i := 0; i < int(*repeat); i++ {
        err = execQuery(st)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    flag.Usage = usage
    flag.Parse()
    if *connStr == "" {
        fmt.Fprintln(os.Stderr, "-conn is required")
        flag.Usage()
    }

    if err := dbOperations(); err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
}

Documentation

Overview

Package odbc implements database/sql driver to access data via odbc interface.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsError

func IsError(ret api.SQLRETURN) bool

func NewError

func NewError(apiName string, handle interface{}) error

func ToHandleAndType

func ToHandleAndType(handle interface{}) (h api.SQLHANDLE, ht api.SQLSMALLINT)

Types

type BaseColumn

type BaseColumn struct {
	CType api.SQLSMALLINT
	// contains filtered or unexported fields
}

BaseColumn implements common column functionality.

func (*BaseColumn) Name

func (c *BaseColumn) Name() string

func (*BaseColumn) Value

func (c *BaseColumn) Value(buf []byte) (driver.Value, error)

type BindableColumn

type BindableColumn struct {
	*BaseColumn
	IsBound         bool
	IsVariableWidth bool
	Size            int
	Len             BufferLen
	Buffer          []byte
}

BindableColumn allows access to columns that can have their buffers bound. Once bound at start, they are written to by odbc driver every time it fetches new row. This saves on syscall and, perhaps, some buffer copying. BindableColumn can be left unbound, then it behaves like NonBindableColumn when user reads data from it.

func NewBindableColumn

func NewBindableColumn(b *BaseColumn, ctype api.SQLSMALLINT, bufSize int) *BindableColumn

func (*BindableColumn) Bind

func (c *BindableColumn) Bind(h api.SQLHSTMT, idx int) (bool, error)

func (*BindableColumn) Value

func (c *BindableColumn) Value(h api.SQLHSTMT, idx int) (driver.Value, error)

type BufferLen

type BufferLen api.SQLLEN

func (*BufferLen) Bind

func (l *BufferLen) Bind(h api.SQLHSTMT, idx int, ctype api.SQLSMALLINT, buf []byte) api.SQLRETURN

func (*BufferLen) GetData

func (l *BufferLen) GetData(h api.SQLHSTMT, idx int, ctype api.SQLSMALLINT, buf []byte) api.SQLRETURN

func (*BufferLen) IsNull

func (l *BufferLen) IsNull() bool

type Column

type Column interface {
	Name() string
	Bind(h api.SQLHSTMT, idx int) (bool, error)
	Value(h api.SQLHSTMT, idx int) (driver.Value, error)
}

Column provides access to row columns.

func NewColumn

func NewColumn(h api.SQLHSTMT, idx int) (Column, error)

func NewVariableWidthColumn

func NewVariableWidthColumn(b *BaseColumn, ctype api.SQLSMALLINT, colWidth api.SQLULEN) Column

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

func (*Conn) Begin

func (c *Conn) Begin() (driver.Tx, error)

func (*Conn) Close

func (c *Conn) Close() error

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (driver.Stmt, error)

func (*Conn) PrepareODBCStmt

func (c *Conn) PrepareODBCStmt(query string) (*ODBCStmt, error)

type DiagRecord

type DiagRecord struct {
	State       string
	NativeError int
	Message     string
}

func (*DiagRecord) String

func (r *DiagRecord) String() string

type Driver

type Driver struct {
	Stats
	// contains filtered or unexported fields
}

func (*Driver) Close

func (d *Driver) Close() error

func (*Driver) Open

func (d *Driver) Open(dsn string) (driver.Conn, error)

type Error

type Error struct {
	APIName string
	Diag    []DiagRecord
}

func (*Error) Error

func (e *Error) Error() string

type NonBindableColumn

type NonBindableColumn struct {
	*BaseColumn
}

NonBindableColumn provide access to columns, that can't be bound. These are of character or binary type, and, usually, there is no limit for their width.

func (*NonBindableColumn) Bind

func (c *NonBindableColumn) Bind(h api.SQLHSTMT, idx int) (bool, error)

func (*NonBindableColumn) Value

func (c *NonBindableColumn) Value(h api.SQLHSTMT, idx int) (driver.Value, error)

type ODBCStmt

type ODBCStmt struct {
	Parameters []Parameter
	Cols       []Column
	// contains filtered or unexported fields
}

func (*ODBCStmt) BindColumns

func (s *ODBCStmt) BindColumns() error

func (*ODBCStmt) Exec

func (s *ODBCStmt) Exec(args []driver.Value) error

type Parameter

type Parameter struct {
	SQLType api.SQLSMALLINT
	Decimal api.SQLSMALLINT
	Size    api.SQLULEN

	// Following fields store data used later by SQLExecute.
	// The fields keep data alive and away from gc.
	Data             interface{}
	StrLen_or_IndPtr api.SQLLEN
	// contains filtered or unexported fields
}

func ExtractParameters

func ExtractParameters(h api.SQLHSTMT) ([]Parameter, error)

func (*Parameter) BindValue

func (p *Parameter) BindValue(h api.SQLHSTMT, idx int, v driver.Value) error

func (*Parameter) StoreStrLen_or_IndPtr

func (p *Parameter) StoreStrLen_or_IndPtr(v api.SQLLEN) *api.SQLLEN

StoreStrLen_or_IndPtr stores v into StrLen_or_IndPtr field of p and returns address of that field.

type Result

type Result struct {
	// contains filtered or unexported fields
}

func (*Result) LastInsertId

func (r *Result) LastInsertId() (int64, error)

func (*Result) RowsAffected

func (r *Result) RowsAffected() (int64, error)

type Rows

type Rows struct {
	// contains filtered or unexported fields
}

func (*Rows) Close

func (r *Rows) Close() error

func (*Rows) Columns

func (r *Rows) Columns() []string

func (*Rows) Next

func (r *Rows) Next(dest []driver.Value) error

type Stats

type Stats struct {
	EnvCount  int
	ConnCount int
	StmtCount int
	// contains filtered or unexported fields
}

type Stmt

type Stmt struct {
	// contains filtered or unexported fields
}

func (*Stmt) Close

func (s *Stmt) Close() error

func (*Stmt) Exec

func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)

func (*Stmt) NumInput

func (s *Stmt) NumInput() int

func (*Stmt) Query

func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

func (*Tx) Commit

func (tx *Tx) Commit() error

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL