You need to enable JavaScript to run this app.
导航

ByteHouse Go Driver

最近更新时间2024.03.01 16:58:33

首次发布时间2023.07.27 10:36:33

本文介绍如何通过 ByteHouse Go Driver 连接并访问 ByteHouse 云数仓。
请访问 github 项目主页,获取 ByteHouse Go 驱动最新的文档和发布版本。

连接到 ByteHouse

请参考通过驱动连接到 ByteHouse,了解如何通过API Token 或用户名+密码的方式连接到 ByteHouse 。

基本使用

创建一个数据库和数据表。

说明

参考使用时,需编辑“host:port”和“api token”的字段。

package main 

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

    _ "github.com/bytehouse-cloud/driver-go/sql" 
)
 
func main() { 
    dsn := fmt.Sprintf("tcp://{HOST}:{PORT}?secure=true&user=bytehouse&password={API_KEY}") 
//If user wishes to specify the database in url 
    dsn := fmt.Sprintf("tcp://{HOST}:{PORT}?secure=true&user=bytehouse&password={API_KEY}&database={DATABASE}")

    db, err := sql.Open("bytehouse", dsn)
    if err != nil {
       fmt.Println("failed to open db", err)
       return
    }
    
    defer db.Close()
    
    ctx := context.Background()
    // create database query
    createDBQuery := `
       CREATE database if not exists my_db`
    _, err = db.ExecContext(ctx, createDBQuery)
    if err != nil {
       log.Fatal("failed to execute create database query\n", err)
       return
    }
    
    // create table query
    createTableQuery := `
       CREATE TABLE IF NOT EXISTS my_db.animal
                  (
                      dog Int64,
                      cat Int64
                  )
                  ENGINE=CnchMergeTree ORDER BY dog
    `
    _, err = db.ExecContext(ctx, createTableQuery)
    if err != nil {
       log.Fatal("failed to execute create table query\n", err)
       return
    }
} 

插入数据

将值插入到新建的表中。

说明

参考使用时,需编辑“host:port”和“api token”的字段。

package main 
import ( 
    "context"
    "database/sql"
    "fmt"
    
    bytehouse "github.com/bytehouse-cloud/driver-go"
    "github.com/bytehouse-cloud/driver-go/sdk"
    
    _ "github.com/bytehouse-cloud/driver-go/sql"
    sql2 "github.com/bytehouse-cloud/driver-go/sql" 
)
 
func main() { 
    dsn := fmt.Sprintf("tcp://{HOST}:{PORT}?secure=true&user=bytehouse&password={API_KEY}") 
//If user wishes to specify the database in url 
    dsn := fmt.Sprintf("tcp://{HOST}:{PORT}?secure=true&user=bytehouse&password={API_KEY}&database={DATABASE}") 
 
    db, err := sql.Open("bytehouse", dsn)
    if err != nil {
       fmt.Println("failed to open db", err)
       return
    }
    
    defer db.Close()
    
    // set the insert block size if needed
    ctx := bytehouse.NewQueryContext(context.Background())
    batchSize := 10
    if err != ctx.AddClientSetting(bytehouse.InsertBlockSize, batchSize) {
       fmt.Println("failed to add client setting", err)
       return
    }
    
    if err = sql2.RunConn(ctx, db, func(conn sdk.Conn) error {
       stmt, err := conn.PrepareContext(ctx, "INSERT INTO my_db.animal VALUES (?, ?)")
       if err != nil {
          return err
       }
    
       rows := 100
       for i := 0; i < rows; i++ {
          if err := stmt.ExecContext(ctx, 1, 2); err != nil {
             return err
          }
       }
    
       return stmt.Close() // Remember to close the stmt! This step is a must for the query to go through!
    }); err != nil {
       fmt.Printf("error = %v", err)
    }
    
    return
 
} 

数据查询

说明

参考使用时,需编辑“host:port”和“api token”的字段。

package main 
import ( 
    "context"
    "database/sql"
    "fmt"
    "log"
    
    _ "github.com/bytehouse-cloud/driver-go/sql"
) 
func main() { 
    dsn := fmt.Sprintf("tcp://{HOST}:{PORT}?secure=true&user=bytehouse&password={API_KEY}") 
//If user wishes to specify the database in url 
    dsn := fmt.Sprintf("tcp://{HOST}:{PORT}?secure=true&user=bytehouse&password={API_KEY}&database={DATABASE}") 
 
    db, err := sql.Open("bytehouse", dsn)
    if err != nil {
       fmt.Println("failed to open db", err)
       return
    }
    
    defer db.Close()
    
    // Perform a SELECT query
    ctx := context.Background()
    rows, err := db.QueryContext(ctx, "SELECT * FROM my_db.animal")
    if err != nil {
       log.Fatal(err)
    }
    defer rows.Close()
    
    // Iterate over the result set and print each row
    for rows.Next() {
       // Create a slice of `driver.Value` to hold the values of the current row
       var values []interface{}
    
       // Replace the following placeholders with the actual types of your columns
       var col1, col2 int64
    
       values = append(values, &col1, &col2)
    
       // Use `rows.Scan` to populate the values slice with the values of the current row
       err := rows.Scan(values...)
       if err != nil {
          log.Fatal(err)
       }
    
       // Process the values as needed
       fmt.Println(col1, col2)
    }
    
    // Check for errors from iterating over rows
    if err = rows.Err(); err != nil {
       log.Fatal(err)
    }
 
}