godror基于ODPI-C的 oracle golang 驱动使用
godror 是一个很不错的oracle golang 驱动,基于ODPI-C 编写,好处是我们需要需要依赖编译
我们只需要安装oracle client 就可以了,不像go-oci8需要编译,同时目前也有一个纯golang 的
oracle驱动,但是目前还不是很稳定,以下是godror的参考使用
参考代码
package main
import (
"database/sql"
"flag"
"fmt"
_ "github.com/godror/godror"
"log"
)
var (
username = flag.String("uname", "scott", "oracle username")
password = flag.String("password", "tiger", "oracle password")
oraclehost = flag.String("oraclehost", "dbhost", "oracle database host")
oracleport = flag.Int("oracleport", 1521, "oracle database port")
dbname = flag.String("dbname", "orclpdb1", "oracle database name")
)
func main() {
flag.Parse()
osqlInfo := fmt.Sprintf("%s/%s@%s:%d/%s", *username, *password, *oraclehost, *oracleport, *dbname)
db, err := sql.Open("godror", osqlInfo)
if err != nil {
log.Fatalf("connect oracle db error: %s:", err.Error())
}
rows, err := db.Query("select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') AS name from dual")
if err != nil {
fmt.Println("exec query error:", err.Error())
}
for rows.Next() {
var name string
rows.Scan(&name)
fmt.Println("fetch item:")
fmt.Println(name)
}
}
运行
go run main.go -uname <username> -password <password> -oraclehost <ip> -dbname <db>
docker 构建
使用了oracle 官方的linux 作为基础镜像
FROM golang:1.15-buster as build
WORKDIR /go/src/app
ENV GO111MODULE=on
ENV GOPROXY=https://goproxy.cn
COPY . .
RUN go build
FROM oraclelinux:7-slim
ARG release=19
ARG update=9
RUN yum -y install oracle-release-el7 && \
yum -y install oracle-instantclient${release}.${update}-basic && \
rm -rf /var/cache/yum
COPY --from=build /go/src/app/mygolang-oracle /mygolang-oracle
ENTRYPOINT [ "/mygolang-oracle" ]
说明
以上的docker 构建使用了多阶段,使用oraclelinux进行运行,主要是简单,而且内置了好多oracle 的依赖,不需要我们
进行多复杂的处理,sijms/go-ora 的golang纯golang 代码驱动是一个不错的选择,但是期待稳定
参考资料
https://github.com/rongfengliang/godror-golang-learning
https://godror.github.io/godror/doc/tuning.html#-query-performance
https://oracle.github.io/odpi/doc/installation.html#id10
https://github.com/godror/godror
https://hub.docker.com//oraclelinux
https://hub.docker.com//golang
https://github.com/sijms/go-ora