Go 使用 go-oci8 访问 Oracle 示例
2017-11-09 本文已影响1200人
custa
一、Linux 开发环境
- 环境
- SLE12-SP1
- go 1.8
- git 2.10.0 能访问 GitHub
- gcc 4.8.5
- pkg-config 0.28
- 安装 Oracle Instant Client -- 从 Oracle 官网 下载 zip 包并解压
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
- 下载 go-oci8 及依赖包
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
- 示例代码 sql.go
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
- 修改 pc 文件
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
- 设置主机名,解决以下问题
ORA-21561: OID generation failed (12.1.0.2.0)
ORA-24454: client host name is not set (12.2.0.1.0)
echo "127.0.0.1 $(hostname)" >>/etc/hosts
- 运行
./sql <username>/<password>@<IP>:<port>/<instance>