connect oracle database with golang in mac os
coding in mac os ,build go file ,test connect to oracle db
在mac os上編寫(xiě)go代碼剑逃,測(cè)試連接oracle數(shù)據(jù)庫(kù)
下載 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
解壓縮
解壓縮兩個(gè)文件即舌,并且合并到一個(gè)目錄中结洼。
/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
鏈接失敗,執(zhí)行
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
或者通過(guò)brew安裝
sudo brew install pkg-config
./configure --with-internal-glib
make
sudo make install
新建oci8.pc
內(nèi)容如下
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
設(shè)置環(huán)境變量
PKG_CONFIG_PATH=/Users/nagatyase/instantclient_11_2
LD_LIBRARY_PATH=/Users/nagatyase/instantclient_11_2
執(zhí)行測(cè)試
go get github.com/mattn/go-oci8
編寫(xiě)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