Go语言访问Oracle

基础环境准备

  • oracle客户端部署
    不在此说明,请自行安装。

  • 安装go-oci8

//查看oracle环境变量
# env |grep ORA
ORACLE_DOC=/oracle/product/11.2.0.3/db_1/doc
ORACLE_SID=dbnms
ORACLE_BASE=/oracle/product
ORACLE_HOME=/oracle/product/11.2.0.3/db_1

//在lib/pkg-config目录下新建oci8.pc文件
# cd /oracle/product/11.2.0.3/db_1/lib/
# mkdir pkg-config
# cd pkg-config/
# vi oci8.pc
prefix=/oracle
libdir=/oracle/product/11.2.0.3/db_1/lib
includedir=/oracle/product/11.2.0.3/db_1

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: 11.2
# export PKG_CONFIG_PATH=$ORACLE_HOME/lib/pkg-config

//获取go-oci8包
# go get github.com/mattn/go-oci8

安装oci8时,可能出现以下错误:

# github.com/mattn/go-oci8
/slview/nms/go/src/github.com/mattn/go-oci8/oci8.go:4:17: fatal error: oci.h: No such file or directory
 #include 
                 ^
compilation terminated.

需要修改includedir为oci.h实际路径:

//查询oci.h所在路径
# locate oci.h
/oracle/product/11.2.0.3/db_1/precomp/public/sql2oci.h
/oracle/product/11.2.0.3/db_1/rdbms/public/oci.h
/usr/include/Qt/qsql_oci.h
/usr/include/QtSql/qsql_oci.h

//修改includedir为实际路径
# vi oci8.pc 
...
includedir=/oracle/product/11.2.0.3/db_1/rdbms/public
...

//重新获取go-oci8包
# go get github.com/mattn/go-oci8
  • 测试示例:
package main

import (
    "database/sql"
    "log"

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

func main() {
    //修改成自己数据账号及密码
    db, err := sql.Open("oci8", "scott/12345@dbnms")
    if err != nil {
        log.Fatal(err)
    }
    rows, err := db.Query("select * from dual")
    defer rows.Close()
    if err != nil {
        log.Fatal(err)
    }
    for rows.Next() {
        var i string
        err = rows.Scan(&i)
        if err != nil {
            log.Fatal(err)
        }
        println(i)
    }
}

测试结果:

$go build testConOracle.go
$ ./testConOracle 
X

你可能感兴趣的:(Go语言访问Oracle)