跳转到主要内容

如何使用 Go 语言与 Databend 交互

准备工作

创建 Databend 用户

mysql -h127.0.0.1 -uroot -P3307

创建用户

CREATE USER user1 IDENTIFIED BY 'abc123';

授予权限

Grants ALL privileges to the user user1:

GRANT ALL on *.* TO user1;

Go

本指南将会展示如何使用 Go 语言连接 Databend 并执行查询。 我们将创建一个名为 books 的表并插入一行数据,然后进行查询。

main.go

main.go
package main

import (
"database/sql"
"fmt"
"log"

_ "github.com/go-sql-driver/mysql"
)

const (
username = "user1"
password = "abc123"
hostname = "127.0.0.1:3307"
)

type Book struct {
Title string
Author string
Date string
}

func dsn() string {
// Note Databend do not support prepared statements.
// set interpolateParams to make placeholders (?) in calls to db.Query() and db.Exec() interpolated into a single query string with given parameters.
// ref https://github.com/go-sql-driver/mysql#interpolateparams
return fmt.Sprintf("%s:%s@tcp(%s)/?interpolateParams=true", username, password, hostname)
}

func main() {
db, err := sql.Open("mysql", dsn())

if err != nil {
log.Fatal(err)
}
defer db.Close()

err = db.Ping()
if err != nil {
log.Fatal(err)
}
log.Println("Connected")

// Create db if do not exist
dbSql := "CREATE DATABASE IF NOT EXISTS book_db"
_, err = db.Exec(dbSql)
if err != nil {
log.Fatal(err)
}
log.Println("Create database book_db success")

// Use book_db database
_, err = db.Exec("USE book_db")
if err != nil {
log.Fatal(err)
}

// Create table.
sql := "create table if not exists books(title VARCHAR, author VARCHAR, date VARCHAR)"
_, err = db.Exec(sql)
if err != nil {
log.Fatal(err)
}
log.Println("Create table: books")

// Insert 1 row.
_, err = db.Exec("INSERT INTO books VALUES(?, ?, ?)", "mybook", "author", "2022")
if err != nil {
log.Fatal(err)
}
log.Println("Insert 1 row")

// Select.
res, err := db.Query("SELECT * FROM books")
if err != nil {
log.Fatal(err)
}

for res.Next() {
var book Book
err := res.Scan(&book.Title, &book.Author, &book.Date)
if err != nil {
log.Fatal(err)
}

log.Printf("Select:%v", book)
}

}

Golang mod

go mod init databend-golang
go.mod
module databend-golang

go 1.18

require github.com/go-sql-driver/mysql v1.6.0

运行 main.go

go run main.go
Outputs
2022/04/13 12:20:07 Connected
2022/04/13 12:20:07 Create database book_db success
2022/04/13 12:20:07 Create table: books
2022/04/13 12:20:07 Insert 1 row
2022/04/13 12:20:08 Select:{mybook author 2022}