截至目前(2022-05-26),GBase 8a尚未发布go语言的驱动,本文尝试通过go-sql-driver/mysql驱动来访问GBase 8a数据库。
目录导航
Go 驱动安装
从github.com下载驱动
E:\go\hello>go get github.com/go-sql-driver/mysql
go: downloading github.com/go-sql-driver/mysql v1.6.0
go: added github.com/go-sql-driver/mysql v1.6.0
Go 代码
来自于官网的样例 https://go.dev/doc/tutorial/database-access
注意其中增加了 AllowNativePasswords: true 的配置,否则会报错
[mysql] 2022/05/26 14:46:43 connector.go:95: could not use requested auth plugin 'mysql_native_password': this user requires mysql native password authentication.
2022/05/26 14:46:43 this user requires mysql native password authentication.
package main
import (
"database/sql"
"fmt"
"log"
"os"
"github.com/go-sql-driver/mysql"
)
var db *sql.DB
type TableT1 struct {
ID int64
NAME string
}
func main() {
// Capture connection properties.
cfg := mysql.Config{
User: os.Getenv("DBUSER"),
Passwd: os.Getenv("DBPASS"),
Net: "tcp",
Addr: "192.168.56.1:5258",
DBName: "testdb",
AllowNativePasswords: true,
}
// Get a database handle.
var err error
db, err = sql.Open("mysql", cfg.FormatDSN())
if err != nil {
log.Fatal(err)
}
pingErr := db.Ping()
if pingErr != nil {
log.Fatal(pingErr)
}
fmt.Println("Connected!")
tableT1s, err := selectTable("1")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Albums found: %v\n", tableT1s)
}
func selectTable(name string) ([]TableT1, error) {
// An tableT1s slice to hold data from returned rows.
var tableT1s []TableT1
rows, err := db.Query("SELECT * FROM t1 WHERE id = ?", name)
if err != nil {
return nil, fmt.Errorf("selectTable %q: %v", name, err)
}
defer rows.Close()
// Loop through rows, using Scan to assign column data to struct fields.
for rows.Next() {
var alb TableT1
if err := rows.Scan(&alb.ID,&alb.NAME); err != nil {
return nil, fmt.Errorf("selectTable %q: %v", name, err)
}
tableT1s = append(tableT1s, alb)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("selectTable %q: %v", name, err)
}
return tableT1s, nil
}
GBase 8a表
2个字段的表,没有采用官网的表结构
gbase> desc testdb.t1;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | YES | MUL | NULL | |
| name | varchar(100) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (Elapsed: 00:00:00.00)
gbase> select * from testdb.t1 where id=1;
+------+---------+
| id | name |
+------+---------+
| 1 | Name_10 |
+------+---------+
1 row in set (Elapsed: 00:00:00.01)
执行
E:\go\hello>go run .
Connected!
Albums found: [{1 Name_10}]
E:\go\hello>