?awsdb=
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.126)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = awsdb)
)
)
EXTPROC_CONNECTION_DATA =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
)
(CONNECT_DATA =
(SID = PLSExtProc)
(PRESENTATION = RO)
)
)
?2.1、增删改查
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-oci8"
"os"
)
func main() {// 字符集os.Setenv("NLS_LANG", "AMERICAN_AMERICA.AL32UTF8")
// 注意连接字符串的写法
db, err := sql.Open("oci8", "awsdb/awsdb@192.168.0.126:1521/awsdb")
if err != nil {
fmt.Println(err)
return
}
// 事务开启
myTx,err:=db.Begin()
myTx.Commit()
// 查询与结果遍历rows, err := db.Query("select nodeid,nodename from AA_MT_TEST")
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
var f1 string
var f2 string
rows.Scan(&f1, &f2)
println(f1, f2) // 3.14 foo
}
rows.Close()
_, err = db.Exec("create table foo(bar varchar2(256))")
_, err = db.Exec("drop table foo")
if err != nil {
fmt.Println(err)
return
}
// 关闭数据库连接
db.Close()
}
2.2、执行了一个存储过程、使用结构保存结果
package main
import (
"database/sql"
_ "github.com/mattn/go-oci8"
"fmt"
"os"
"sync"
)
var (
db *sql.DB
mux sync.Mutex
)
// 多行字符串的定义
var userTableSql string = `
BEGIN
BEGIN
EXECUTE IMMEDIATE ‘DROP TABLE user_profile‘;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
EXECUTE IMMEDIATE ‘CREATE TABLE user_profile (id int PRIMARY KEY, name VARCHAR(20) NOT NULL, created VARCHAR(20) NOT NULL)‘;
END;
`
func init() {// 锁mux.Lock()
defer mux.Unlock()
os.Setenv("NLS_LANG", "AMERICAN_AMERICA.ZHS16GBK")
// check
if db != nil {
return
}
// open
oracledb, err := sql.Open("oci8", "awsdb/awsdb@192.168.0.126:1521/awsdb")
checkErr(err)
// new db
db = oracledb
// create database table
_, err = db.Exec(userTableSql)
checkErr(err)
}
func checkErr(err error) {
if err != nil {
panic("oracle err:" + err.Error())
}
return
}
func main() {
// insert
insertSql := `insert into user_profile(id,name,created) values(1,‘viney‘,‘2013-03-06‘)`
_, err := db.Exec(insertSql)
checkErr(err)
// update
updateSql := `update user_profile set name=‘中国人‘ where id=1`
_, err = db.Exec(updateSql)
checkErr(err)
// select
querySql := `select * from user_profile where id=1`
rows, err := db.Query(querySql)
type user struct {
id int // 这个地方改成string才不会报错,但是我创建数据库是int类型
name string
created string
}
var u = &user{}
for rows.Next() {
err = rows.Scan(
&u.id,
&u.name,
&u.created)
checkErr(err)
}
rows.Close()
fmt.Println(*u)
// delete
deleteSql := `delete from user_profile where id=1`
_, err = db.Exec(deleteSql)
checkErr(err)
db.Close()
}
?
?
GOLANG 在 UBUNTU 14.04 上使用 Oracle 数据库,布布扣,bubuko.com
GOLANG 在 UBUNTU 14.04 上使用 Oracle 数据库
原文地址:http://blog.csdn.net/guo_rui22/article/details/25724413