美文网首页
golang mac os 连接oracle数据库

golang mac os 连接oracle数据库

作者: luckyase | 来源:发表于2018-07-17 15:04 被阅读0次

    connect oracle database with golang in mac os

    coding in mac os ,build go file ,test connect to oracle db

    在mac os上编写go代码,测试连接oracle数据库

    下载 instantclient

    instantclient-basic-macos.x64-11.2.0.4.0
    instantclient-sdk-macos.x64-11.2.0.4.0
    download http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html

    解压缩

    解压缩两个文件,并且合并到一个目录中。
    /Users/nagatyase/instantclient_11_2
    /Users/nagatyase/instantclient_11_2/sdk

    拷贝,链接

    cd /Users/nagatyase/instantclient_11_2
    cp libclntsh.dylib.11.1 libclntsh.dylib
    ln libclntsh.dylib /usr/lib/libclntsh.dylib
    ln libocci.dylib.11.1 /usr/lib/libocci.dylib
    ln libociei.dylib /usr/lib/libociei.dylib
    ln libnnz11.dylib /usr/lib/libnnz11.dylib
    

    链接失败,执行

    sudo chown -R $(whoami)
    sudo chown -R $(whoami) /usr/lib
    

    下载 pkg-config

    download https://lists.freedesktop.org/archives/pkg-config/2017-March/001084.html
    Guide to pkg-config https://people.freedesktop.org/~dbn/pkg-config-guide.html#faq
    或者通过brew安装

    sudo brew install pkg-config
    
    ./configure  --with-internal-glib
     make
     sudo make install
    

    新建oci8.pc

    内容如下

    prefixdir=/Users/nagatyase/instantclient_11_2
    libdir=${prefixdir}
    includedir=${prefixdir}/sdk/include
    Name: OCI
    Description: Oracle database driver
    Version: 12.2
    Libs: -L${libdir} -lclntsh
    Cflags: -I${includedir}
    

    oci8.pc 位置
    /Users/nagatyase/instantclient_11_2

    设置环境变量

    PKG_CONFIG_PATH=/Users/nagatyase/instantclient_11_2
    LD_LIBRARY_PATH=/Users/nagatyase/instantclient_11_2
    

    执行测试

    go get github.com/mattn/go-oci8
    

    编写oracle_db.go

    package main
    
    import (
        "fmt"
        _ "github.com/mattn/go-oci8"
        "database/sql"
    )
    
    func main() {
        db, err := sql.Open("oci8", "username/pwd@ip:1521/dbname")
        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)
        }
    }
    
    go run oracle_db.go
    2 + 2 always equals: 4
    

    相关文章

      网友评论

          本文标题:golang mac os 连接oracle数据库

          本文链接:https://www.haomeiwen.com/subject/yiowpftx.html