Skip to main content

How to Work with Databend in Golang

Before You Begin

Create Databend User

mysql -h127.0.0.1 -uroot -P3307

Create a User

mysql>
create user user1 identified by 'abc123';

Grants Privileges

Grants ALL privileges to the user user1:

mysql>
grant all on *.* to 'user1';

Golang

This guideline show how to connect and query to Databend using Golang. We will be creating a table named books and insert a row, then query it.

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(255), author varchar(255), date varchar(255))"
_, 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

Run 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}