Bootstrap

mattn / go-oci8 库安装 (用于go连接oracle数据库)

  • mattn/go-oci8 库用于连接oracle数据库,项目地址为:

https://github.com/mattn/go-oci8

  • 安装步骤如下:

1. 从oracle官网下载oracleClient、SDK

https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html

2. 下载mattn/go-oci8项目

$ go git github.com/mattn/go-oci8

3. 编辑oci8.pc文件内容

prefix=/devel/target/XXXXXXXXXXXXXXXXXXXXXXXXXX
exec_prefix=${prefix}
libdir=/opt/instantclient_11_2
includedir=/opt/instantclient_11_2/sdk/include

glib_genmarshal=glib-genmarshal
gobject_query=gobject-query
glib_mkenums=glib-mkenums

Name: oci8
Description: oci8 library
Libs: -L${libdir} -lclntsh
Cflags: -I${includedir}
Version: 12.2
  • libdir为instantclient的客户端lib库目录路径
  • includedir为客户端的库头文件目录路径

4.设置相关环境变量

  • LD_LIBRARY_PATH :设置为instantclient的客户端lib库目录路径
  • PKG_CONFIG_PATH :设置为oci8.pc文件所在目录路径

5.安装go-oci8模块

 $  go install github.com/mattn/go-oci8

6.验证代码

代码如下:

package main
import (
        "database/sql"
        "log"
        "fmt"
        _ "github.com/mattn/go-oci8"
)

func main(){
        sqlconn := "demo/[email protected]:1521/orcl"
        db, err := sql.Open("oci8", sqlconn)
        if err != nil {
                log.Fatalln(err)
        }
        defer db.Close()
        sql := "select sysdate from dual"
        rows, err := db.Query(sql)
        if err != nil {
                log.Fatalln(err)
        }
        defer rows.Close()

        for rows.Next() {
                var re string
                rows.Scan(&re)
                fmt.Println(re)
        }
        if err = rows.Err(); err != nil {
                log.Fatalln(err)
        }
}

执行结果如下:

2020-02-10T09:13:55Z

  • 为了方便,我将步骤封装为docker镜像,其docker镜像文件描述如下:
FROM centos:7
RUN yum install -y gcc libaio-devel
ENV GOROOT=/opt/go
ENV GOPATH=/opt/
ENV PATH=$PATH:$GOROOT/bin
ENV LD_LIBRARY_PATH=/opt/instantclient_19_5/
ENV PKG_CONFIG_PATH=/opt
ADD ./* /opt/
RUN go install github.com/mattn/go-oci8
;