Golang 连贯 Oracle 须要装置 Oracle Full Client 或 Instant Client 驱动程序
Linux 装置 Golang Oracle 数据库驱动程序
MacBook 装置 Golang Oracle 数据库驱动程序
形式一
应用 go get github.com/mattn/go-oci8
在 GoPath 的 src 目录下创立 oracleoci8.go, 内容如下:
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-oci8"
"log"
"os"
)
func main() {if len(os.Args) != 2 {log.Fatalln(os.Args[0] + "user/password@host:port/sid")
}
fmt.Println(os.Args[1])
db, err := sql.Open("oci8", os.Args[1])
if err != nil {log.Fatalln(err)
}
defer db.Close()
// 查问用户
rows, err := db.Query("select user from dual")
if err != nil {log.Fatalln(err)
}
defer rows.Close()
for rows.Next() {
var data string
rows.Scan(&data)
fmt.Println(data)
}
if err = rows.Err(); err != nil {log.Fatalln(err)
}
// 查问 ZHUJI 表的 code 字段
rows2, err := db.Query("SELECT code FROM ZHUJI")
if err != nil {log.Fatalln(err)
}
defer rows2.Close()
for rows2.Next() {
var data string
rows2.Scan(&data)
fmt.Println(data)
}
if err = rows2.Err(); err != nil {log.Fatalln(err)
}
}
运行
# 间接运行
go run oracleoci8.go liang/liang@192.168.0.4:1521/orcl
#或者先编译成二进制, 在运行二进制文件
go build oracleoci8.go
./oracleoci8 liang/liang@192.168.0.4:1521/orcl
形式二
应用 go get github.com/godror/godror
在 GoPath 的 src 目录下创立 oracledror.go, 内容如下:
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/godror/godror"
)
func main() {db, err := sql.Open("godror", `user="liang" password="liang" connectString="192.168.0.4:1521/orcl"`)
if err != nil {panic(err)
}
err = db.Ping()
if err != nil {panic(err)
}
// 查问 ZHUJI 表中 code='pt' 的 sql:SELECT * FROM ZHUJI where CODE = 'pt'
sqlStatement := "SELECT * FROM ZHUJI where CODE = :1"
stmt, err := db.Prepare(sqlStatement)
defer stmt.Close()
if err != nil {panic(err)
}
rows, err := stmt.Query("pt") // 输出 sql 中对应参数的值
if err != nil {panic(err)
}
defer rows.Close() //defer 敞开查问连贯
// 获取列相干信息
strings, _ := rows.Columns()
for i := 0; i < len(strings); i++ {fmt.Print(" ", strings[i])
}
fmt.Print("\n")
// 结构切片存储 json
var slice []map[string]interface{}
var m1 map[string]interface{}
m1 = make(map[string]interface{})
var CODE, OVALUE1, OVALUE2 string
for rows.Next() {rows.Scan(&CODE, &OVALUE1, &OVALUE2) // 写入查问数据集的所有列名称
fmt.Printf("code is %s, OVALUE1 is %s\n", CODE, OVALUE1)
m1["CODE"] = CODE
m1["OVALUE1"] = OVALUE1
m1["OVALUE2"] = OVALUE2
slice = append(slice, m1) // 分片中追加信息
}
if err = rows.Err(); err != nil {// handle the error here}
defer stmt.Close()
data, err := json.Marshal(slice)
if err != nil {fmt.Printf("序列化谬误 err = %v\n", err)
}
// 输入序列化后的后果 json 字符串
fmt.Printf("序列化后 = %v\n", string(data))
}
运行
# 间接运行
go run oracledror.go
#或者先编译成二进制, 在运行二进制文件
go build oracledror.go
./oracledror