一、需求

Go使用OCI8访问oracle

二、环境准备

系统:CentOS Linux release 7.9.2009 (Core)
Go版本:go version go1.17.2 linux/amd64

  1. 安装oracle client(sqlplus)

用于访问oracle

rpm -ivh oracle-instantclient-basic-21.3.0.0.0-1.x86_64.rpm

配置环境变量

echo 'export LD_LIBRARY_PATH=/usr/lib/oracle/21/client64/lib' >> /etc/profile
source /etc/profile
  1. 安装gcc/gcc-c++

用于编译

yum install gcc gcc-c++ -y 
  1. 安装pkg-config

用于管理指定OCI8的相关库

yum install pkg-config -y 

配置OCI8 PkgConfig文件

mkdir /usr/local/lib/pkconfig/
vim /usr/local/lib/pkconfig/oci8.pc

prefix=/usr
exec_prefix=${prefix}
libdir=${prefix}/lib/oracle/21/client64/lib  #sqlplus客户端库路径
includedir=${prefix}/include/oracle/21/client64  #客户端路径

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: 21

配置OCI8 PkgConfig文件环境变量

echo 'export PKG_CONFIG_PATH=/usr/local/lib/pkconfig/' >> /etc/profile
source /etc/profile

三、go连接oracle测试


package main
import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-oci8"
)
var db *sql.DB
func initDB() (err error) {
// dsn 用户名/密码@oracle机器IP:端口/服务名
    dsn := "monitor/oracle@192.168.20.132:1521/five"
    db, err = sql.Open("oci8", dsn)
    if err != nil {
        return err
    }
    // 尝试与数据库建立连接(校验dsn是否正确)
    err = db.Ping()
    if err != nil {
        return err
    }
    return nil
}
func main() {
    err := initDB()
    if err != nil {
        fmt.Printf("init db failed,err:%s\n", err)
        return
    }
    defer db.Close()
    var user string
    err = db.QueryRow("select user from dual").Scan(&user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("Successful  connection. Current user is: %v\n", user)
}

在这里插入图片描述