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]) } }