一、系统环境介绍:
Linux archlinux 4.20.11-arch1-1-ARCH
Oracle 11g 64bit
OCI -> instantclient-basic-linux.x64-11.2.0.4.0.zip
OCI SDK -> instantclient-sdk-linux.x64-11.2.0.4.0.zip
go version go1.11 linux/amd64
二、安装pkg-config
# pacman -S pkg-config
三、安装go-oci8
项目开源地址:https://github.com/wendal/go-oci8
四、下载Oracle 的 OCI和SDK
1、下载OCI和SDK
https://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html
下载下面两文件:
instantclient-basic-linux.x64-11.2.0.4.0.zip
instantclient-sdk-linux.x64-11.2.0.4.0.zip
- 将上面的两个压缩文件解压到/usr/instantclient_11_2中,/usr/instantclient_11_2文件夹中内容如下:
adrci genezi libnnz11.so libociei.so ojdbc5.jar sdk xstreams.jar
BASIC_README libclntsh.so.11.1 libocci.so.11.1 libocijdbc11.so ojdbc6.jar uidrvci
- 设置环境变量LD_LIBRARY_PATH:
LD_LIBRARY_PATH=:/usr/instantclient_11_2
五、编辑oci8.pc,配置环境变量PKG_CONFIG_PATH
- 创建oci8.pc文件,放在项目地址如/home/go/src/test/oracle/oci8.pc, 编辑oci8.pc内容如下,确保oracle库文件及头文件地址正确:
prefix=/usr
includedir=${prefix}/instantclient_11_2/sdk/include
libdir=${prefix}/instantclient_11_2
Name: oci8
Description: Oracle Instant Client
Version: 11.2
Cflags: -I${includedir}
Libs: -L${libdir} -lclntsh
- 设置环境变量
PKG_CONFIG_PATH=/home/go/src/test/oracle
六、数据操作测试
测试文件main_test.go,测试前注意先添加userinfo表及数据
package main_test
import (
"database/sql"
"testing"
"github.com/go-xorm/xorm"
_ "github.com/mattn/go-oci8"
)
var driverName = "oci8" //Oracle 驱动
var dataSourceName = "ggs/123456@127.0.0.1:1521/ORCL" //数据库账号:ggs,密码:123456,实例服务:ORCL
var engine *xorm.Engine
func TestXormOracle(t *testing.T) {
var err error
engine, err = xorm.NewEngine(driverName, dataSourceName)
if err != nil {
t.Error(err)
}
tabs, err := engine.DBMetas()
if err != nil {
t.Error(err)
}
println(len(tabs))
}
func TestMattnOracle(t *testing.T) {
var db *sql.DB
var err error
if db, err = sql.Open(driverName, dataSourceName); err != nil {
t.Error(err)
return
}
var rows *sql.Rows
if rows, err = db.Query("select * from userinfo"); err != nil {
t.Error(err)
return
}
defer rows.Close()
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
println(id, name) // 3.14 foo
}
}
1、TestXormOracle测试
=== RUN TestXormOracle
1
--- PASS: TestXormOracle (1.29s)
PASS
Process finished with exit code 0
2、TestMattnOracle测试
=== RUN TestMattnOracle
1 人员1
2 人员2
3 人员3
--- PASS: TestMattnOracle (0.39s)
PASS
Process finished with exit code 0