golang利用oci8库访问Oracle数据库例子。
package main
import (
"fmt"
"log"
"database/sql"
_ "github.com/mattn/go-oci8"
)
func sqlExec(db *sql.DB, sqlStmt string) error {
res, err := db.Exec(sqlStmt)
if err != nil {
return err
}
num, err := res.RowsAffected()
if err != nil {
return err
}
log.Printf("SQL Execute success rows affected %d\n", num)
return nil
}
func sqlQuery(db *sql.DB, sqlStmt string) error {
rows, err := db.Query(sqlStmt)
if err != nil {
return err
}
defer rows.Close()
var n int
for rows.Next() {
var name string
var age int
if err := rows.Scan(&name, &age); err != nil {
return err
}
n ++
log.Printf("row[%d], name=[%s], age=[%d]\n", n, name, age)
}
err = rows.Err()
if err != nil {
return err
}
log.Printf("SQL Query success rows queried %d\n", n)
return nil
}
func main() {
db, err := sql.Open("oci8", fmt.Sprintf("%s/%s@%s", "scott", "tiger", "bej301420.cn.oracle.com:1522/orcl.cn.oracle.com"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := db.Ping(); err != nil {
log.Fatal(err)
}
if err := sqlExec(db, "create table mytest(name varchar2(10), age int, primary key(name))"); err != nil {
log.Fatal(err)
}
if err := sqlExec(db, "insert into mytest(name, age) values('Tom', 20)"); err != nil {
log.Fatal(err)
}
if err := sqlExec(db, "insert into mytest(name, age) values('Jerry', 20)"); err != nil {
log.Fatal(err)
}
if err := sqlQuery(db, "select name, age from mytest"); err != nil {
log.Fatal(err)
}
if err := sqlExec(db, "drop table mytest"); err != nil {
log.Fatal(err)
}
}
运行结果如下:
2019/01/19 12:19:36 SQL Execute success rows affected 0
2019/01/19 12:19:36 SQL Execute success rows affected 1
2019/01/19 12:19:36 SQL Execute success rows affected 1
2019/01/19 12:19:36 row[1], name=[Tom], age=[20]
2019/01/19 12:19:36 row[2], name=[Jerry], age=[20]
2019/01/19 12:19:36 SQL Query success rows queried 2
2019/01/19 12:19:36 SQL Execute success rows affected 0
有疑问加站长微信联系(非本文作者)