Golang连接Oracle数据库有些麻烦,需要C编译器,记录一下完整的步骤。
首先去Oracle官网
https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html
下载instantclient-basic及instantcilient-sdk
我这里下载的是instantclient-sdk-linux.x64-19.5.0.0.0dbru.zip和instantclient-basic-linux.x64-19.5.0.0.0dbru.zip
我将两个文件解压到/opt/oracle/目录下
在/opt/oracle/instantclient_19_5下创建oci8.pc文件,版本根据自己下载的做调整,目录位置根据自己解压的位置调整
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
prefix=/opt/oracle/instantclient_19_5 exec_prefix=${prefix} libdir=${exec_prefix} includedir=${prefix}/sdk/include 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: 19.5 |
然后运行以下命令
1 2 |
export PKG_CONFIG_PATH=/opt/oracle/instantclient_19_5 export LD_LIBRARY_PATH=/opt/oracle/instantclient_19_5 |
继续运行以下命令,需要注意的是,libclntsh.so.19.1需要根据实际的版本调整,不要直接复制
1 2 |
ln -s -f /opt/oracle/instantclient_19_5/libclntsh.so.19.1 /opt/oracle/instantclient_19_5/libclntsh.so ln -s -f /opt/oracle/instantclient_19_5/libocci.so.19.1 /opt/oracle/instantclient_19_5/libocci.so |
安装oci8
1 |
go get github.com/mattn/go-oci8 |
没有报错,然后跑一下样例代码试一下(连接信息需要改成自己的)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package main import ( "fmt" "database/sql" _ "github.com/mattn/go-oci8" "github.com/ant0ine/go-json-rest/rest" "log" "net/http" "strconv" ) func main(){ username :="" password :="" database :="" //数据库连接信息 db, err := sql.Open("oci8", username+"/"+password+"@"+database) if err != nil { fmt.Println(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() var a string = "Hello!" for rows.Next() { var sum int rows.Scan(&sum) result := strconv.Itoa(sum) a="2 + 2 always equals: " + result fmt.Println(a) } api := rest.NewApi() api.Use(rest.DefaultDevStack...) api.SetApp(rest.AppSimple(func(w rest.ResponseWriter, r *rest.Request) { w.WriteJson(map[string]string{"Body": a}) })) log.Fatal(http.ListenAndServe(":8080", api.MakeHandler())) } |
打开浏览器,访问8080端口,可以正常访问