Go 使用 go-oci8 访问 Oracle 示例

2017-11-09  本文已影响1200人  custa

一、Linux 开发环境

  1. SLE12-SP1
  2. go 1.8
  3. git 2.10.0 能访问 GitHub
  4. gcc 4.8.5
  5. pkg-config 0.28
unzip -ojd /usr/lib64  instantclient-basiclite-linux.x64-12.2.0.1.0.zip
ln -snf /usr/lib64/libclntsh.so.12.1 /usr/lib64/libclntsh.so
unzip -ojd /usr/include  instantclient-sdk-linux.x64-12.2.0.1.0.zip
export GOPATH=/home/codes/go
git clone https://github.com/golang/net.git ${GOPATH}/src/golang.org/x/net
git clone https://github.com/mattn/go-oci8.git ${GOPATH}/src/github.com/mattn/go-oci8
cat >sql.go <<\EOF
package main

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

    _ "github.com/mattn/go-oci8"
)

func main() {
    if len(os.Args) != 2 {
        log.Fatalln(os.Args[0] + " user/password@host:port/sid")
    }

    db, err := sql.Open("oci8", os.Args[1])
    if err != nil {
        log.Fatalln(err)
    }
    defer db.Close()

    rows, err := db.Query("select user from dual")
    if err != nil {
        log.Fatalln(err)
    }
    defer rows.Close()

    for rows.Next() {
        var data string
        rows.Scan(&data)
        fmt.Println(data)
    }
    if err = rows.Err(); err != nil {
        log.Fatalln(err)
    }
}
EOF
sed -i -e "s|includedir=.*|includedir=/usr/include|" -e "s|libdir=.*|libdir=/usr/lib64|" \
${GOPATH}/src/github.com/mattn/go-oci8/oci8.pc
# export LD_LIBRARY_PATH=/usr/lib64  # -- 非必须
export PKG_CONFIG_PATH=${GOPATH}/src/github.com/mattn/go-oci8
go build -o sql sql.go

二、Linux 运行环境

unzip -ojd /usr/lib64  instantclient-basiclite-linux.x64-12.2.0.1.0.zip  \
instantclient_12_2/libclntsh.so.12.1  instantclient_12_2/libclntshcore.so.12.1  \
instantclient_12_2/libipc1.so  instantclient_12_2/libmql1.so  \
instantclient_12_2/libnnz12.so  instantclient_12_2/libociicus.so  instantclient_12_2/libons.so
echo "127.0.0.1 $(hostname)" >>/etc/hosts
./sql <username>/<password>@<IP>:<port>/<instance>

参考文档

Go database/sql tutorial

上一篇下一篇

猜你喜欢

热点阅读