金仓数据库KingbaseES客户端编程接口指南-Gokb (5. 程序示例 )

5. 程序示例

以下为几个常用功能的程序示例:

5.1. 连接数据库

package main

import (
    "database/sql"
    "fmt"
    _ "kingbase.com/gokb"
)

const (
    host     = "127.0.0.1"
    port     = 54321
    user     = "system"
    password = "123456"
    dbname   = "TEST"
)

func main() {
    connInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    db, err = sql.Open("kingbase", connInfo)
    if err != nil {
        panic(err)
    }
    err = db.Ping()
    if err != nil {
        panic(err)
    }
    fmt.Println("Connection test success!")
    db.Close()
}

5.2. 获取结果集

package main

import (
    "database/sql"
    "fmt"
    _ "kingbase.com/gokb"
)

const (
    host     = "127.0.0.1"
    port     = 54321
    user     = "system"
    password = "123456"
    dbname   = "TEST"
)

/* 声明表结构 */
type GoTable struct {
    Num  int    `db:"num"`
    Text string `db:"text"`
    Blob []byte `db:"blob"`
    Clob string `db:"clob"`
}


func main() {

    connInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    db, err = sql.Open("kingbase", connInfo)
    if err != nil {
        panic(err)
    }
    err = db.Ping()
    if err != nil {
        panic(err)
    }
    db.Close()

    /* CREATE TABLE temp_golang_test (num INTEGER, text TEXT, blob BLOB, clob CLOB) */
    var data []*GoTable
    rows, err := db.Query("select * from temp_golang_test;")
    defer rows.Close()
    if err != nil {
        return nil, err
    }

    for rows.Next() {
        var row GoTable
        err = rows.Scan(&row.Num, &row.Text, &row.Blob, &row.Clob)
        if err != nil {
            return nil, err
        }

        data = append(data, &row)
    }

    for i := 0; i < len(data); i++ {
        fmt.Println(data[i])
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值