DM 驱动包的配置
1. 安装 DM 驱动包
将提供的 DM 驱动包放在 GOPATH 的 src 目录下。驱动包位于 dmdbms/drivers/go/dm-go-driver.zip 解压到 GPPATH 安装路径的 src 下,如图所示:
2. 安装依赖包
所需 Go 依赖包有两个,text
和 snappy
,从 Git 上把依赖包 clone 到本地,桌面右键【Git Bash Here】打开 Git 命令行窗口,依次下载 text 和 snappy 依赖。
git clone https://github.com/golang/text.git D:/goDev/srcc/golang.org/x/text
git clone https://github.com/golang/snappy D:/goDev/src/github.com/golang/snappy
3.go代码
//Sql语句
CREATE TABLE "SYSDBA"."DPI_DEMO"
(
"C1" INT,
"C2" CHAR(20),
"C3" VARCHAR(50),
"C4" NUMERIC(7,3),
"C5" TIMESTAMP(5),
"C6" CLOB,
"C7" BLOB) STORAGE(ON "MAIN", CLUSTERBTR) ;
/*该例程实现插入数据,修改数据,删除数据,数据查询等基本操作。*/
package main
// 引入相关包
import (
"database/sql"
_ "dm"
"fmt"
"time"
)
var db *sql.DB
var err error
func main() {
driverName := "dm"
dataSourceName := "dm://SYSDBA:SYSDBA@localhost:5236"
if db, err = connect(driverName, dataSourceName); err != nil {
fmt.Println(err)
return
}
if err = insertTable(); err != nil {
fmt.Println(err)
return
}
if err = updateTable(); err != nil {
fmt.Println(err)
return
}
if err = queryTable(); err != nil {
fmt.Println(err)
return
}
if err = deleteTable(); err != nil {
fmt.Println(err)
return
}
if err = disconnect(); err != nil {
fmt.Println(err)
return
}
}
func connect(driverName string, dataSourceName string) (*sql.DB, error) {
var db *sql.DB
var err error
if db, err = sql.Open(driverName, dataSourceName); err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
fmt.Printf("connect to \"%s\" succeed.\n", dataSourceName)
return db, nil
}
func insertTable() error {
var sql = `insert into "SYSDBA"."DPI_DEMO"("C1", "C2", "C3", "C4", "C5") VALUES(:1,:2,:3,:4,:5);`
_, err = db.Exec(sql, "4", "123aaa", "中华书局1","0.123", time.Now())
if err != nil {
return err
}
fmt.Println("insertTable succeed")
return nil
}
func updateTable() error {
var sql = `update "SYSDBA"."DPI_DEMO" set "C4" = :1 where c1 = :2;`
if _, err := db.Exec(sql, 222.125,4); err != nil {
return err
}
fmt.Println("updateTable succeed")
return nil
}
func queryTable() error {
var C1 int
var C2 string
var C3 string
var C4 string
var C5 string
var sql = `select "C1","C2","C3","C4","C5" from "SYSDBA"."DPI_DEMO";`
rows, err := db.Query(sql)
if err != nil {
return err
}
defer rows.Close()
fmt.Println("queryTable results:")
for rows.Next() {
if err = rows.Scan(&C1, &C2, &C3, &C4, &C5); err != nil {
return err
}
fmt.Printf("%v %v %v %v %v\n", C1, C2, C3, C4, C5)
}
return nil
}
func deleteTable() error {
var sql = `delete from "SYSDBA"."DPI_DEMO" where c1 = :1;`
if _, err := db.Exec(sql,4); err != nil {
return err
}
fmt.Println("deleteTable succeed")
return nil
}
/* 关闭数据库连接 */
func disconnect() error {
if err := db.Close(); err != nil {
fmt.Printf("db close failed: %s.\n", err)
return err
}
fmt.Println("disconnect succeed")
return nil
}
达梦支持
有任何问题请到技术社区反馈。
24小时免费服务热线:400 991 6599
达梦技术社区:https://eco.dameng.com