golang通过oci访问oracle数据库
首先需要下载 oracle driver for go that using database/sql
$ go get github.com/mattn/go-oci8
然后下载Oracle Instant Client
解开后得到文件夹,例如:instantclient_19_3
golang访问程序
package main
import (
"fmt"
"log"
"database/sql"
_ "github.com/mattn/go-oci8"
)
const (
username = "scott"
password = "tiger"
connstring = "//xxx.xxx.xxx.xxx:1521/orcl"
)
func main() {
db, err := sql.Open("oci8", fmt.Sprintf("%s/%s@%s", username, password, connstring))
if err != nil {
log.Printf("ERROR: Cannot open [%s/XXXX@%s], err=[%v]\n", username, connstring, err)
return
}
log.Printf("Open [%s/XXXX@%s]\n", username, connstring)
defer db.Close()
if err := db.Ping(); err != nil {
log.Printf("ERROR: Cannot ping database, err=[%v]\n", err)
return
}
var version string
if err := db.QueryRow("SELECT VERSION FROM PRODUCT_COMPONENT_VERSION WHERE PRODUCT LIKE 'Oracle Database%'").Scan(&version); err != nil {
log.Printf("ERROR: Cannot get database version, err=[%v]\n", err)
return
}
log.Printf("Database version [%s]\n", version)
}
Makefile文件
$ cat Makefile
# Oracle Instant Client: https://www.oracle.com/database/technologies/instant-client.html
# go get github.com/mattn/go-oci8
all: testoci
testoci: main.go
LIBRARY_PATH=$(abspath instantclient_19_3) \
LD_LIBRARY_PATH=$(abspath instantclient_19_3) \
LD_RUN_PATH=$(abspath instantclient_19_3) \
C_INCLUDE_PATH=$(abspath instantclient_19_3/include) \
PKG_CONFIG_PATH=$(abspath src/github.com/mattn/go-oci8) \
GOPATH=$(abspath .) \
go build -x
.PHONY: clean
clean:
rm -f testoci
整个目录结构包括
-rw-r--r-- 1 485 Jun 6 03:58 Makefile
drwxr-xr-x 3 4096 Jun 6 03:25 instantclient_19_3
-rw-r--r-- 1 981 Jun 6 03:55 main.go
drwxr-xr-x 3 4096 Jun 6 03:57 pkg
drwxr-xr-x 3 4096 Jun 6 03:57 src
编译运行
$ make && ./testoci
...
2019/06/06 04:08:18 Open [scott/XXXX@//xxx.xxx.xxx.xxx:1521/orcl]
2019/06/06 04:08:18 Database version [12.1.0.2.0]