macos系统,golang连接orcale数据库,安装go-oci8遇到的一些坑

golang连接orcale数据库

Orcale安装在远程服务器(centos7)中,采用docker-compose部署,Navicat连接成功。版本为12.1.0.2.0

docker-compose.yml

 version: '2'
 services:
   oracle:
    image: absolutapps/oracle-12c-ee
    environment:
      - ORACLE_PDB=system
      - ORACLE_PWD=oracle
     - ORACLE_CHARACTERSET=AL32UTF8
	  restart: always
   container_name: oracle
   volumes:
     - /home/docker-compose/oracle/my-docker-data/oracle-11g/data:/u01/app/oracle
    ports:
     - 1521:1521
本机系统为:macOS Sierra
	版本:10.12.6

go-oci8环境:

安装:
instantclient-basic-macos.x64-12.1.0.2.0.zip
instantclient-sdk-macos.x64-12.2.0.1.0-2.zip

下载地址:http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html

instantclient_12_1放在/Users/username/Downloads目录下

下载pkg-config
brew install pkg-config
环境变量配置
LD_LIBRARY_PATH=/Users/username/Downloads/instantclient_12_1
PKG_CONFIG_PATH=pkg-config的执行目录
ORACLE_HOME=/Users/username/Downloads/instantclient_12_1

这里遇到了一个坑,PKG_CONFIG_PATH好多文档配置的是instantclient_12_1的目录,我配置的时候就一直报错,后来改成了pkg-config的执行目录

oci8.pc文件内容为
prefixdir=/Users/username/Downloads/instantclient_12_1
libdir=${prefixdir}
includedir=${prefixdir}/sdk/include

Name: OCI
Description: Oracle database driver
Version: 12.1
Libs: -L${libdir} -lclntsh
Cflags: -I${includedir}
连接目录为/usr/lib
cd /Users/nagatyase/instantclient_11_2
cp libclntsh.dylib.12.1 libclntsh.dylib
ln libclntsh.dylib /usr/lib/libclntsh.dylib
ln libocci.dylib.12.1 /usr/lib/libocci.dylib
ln libociei.dylib /usr/lib/libociei.dylib
ln libnnz12.dylib /usr/lib/libnnz12.dylib

这时运行go程序会报错:

dyld: Library not loaded: @rpath/libclntsh.dylib.12.1
Referenced from: 		/var/folders/46/x39f2fws5xnbtv81qgpp8ck80000gn/T/go-	build787259801/b001/exe/main
Reason: image not found
signal: abort trap

原因:连接目录里缺少libclntsh.dylib.12.1
ls libclntsh.dylib.12.1 libclntsh.dylib.12.1

再次运行go程序的时候报错:

panic: OCIEnvCreate error

goroutine 1 [running]:
github.com/mattn/go-oci8.init.0()
/Users/yuyang/work/go/src/github.com/mattn/go-oci8/globals.go:152 +0x517
exit status 2


Navicat Premium

在这里搞了好久,感觉还是环境变量没有配对。无奈重启了机器,重启以后正常运行,原因可能是环境变量没有生效。

go程序代码:
package main


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

func main() {
	db, err := sql.Open("oci8", "username/password@IP:1521/ORCL")
	if err != nil {
		fmt.Println("abc", 123, err)
		return
	}
	defer db.Close()

	if err = db.Ping(); err != nil {
		fmt.Printf("Error connecting to the database: %s\n", err)
		return
	}

	rows, err := db.Query("select 2+2 from dual")
	if err != nil {
		fmt.Println("Error fetching addition")
		fmt.Println(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var sum int
		rows.Scan(&sum)
		fmt.Printf("2 + 2 always equals: %d\n", sum)
	}
}

你可能感兴趣的:(docker-compose,oracle,golang,go-oci8)