> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 用于 C 和 C++ 的 chDB

> 如何在 C 和 C++ 中安装和使用 chDB

chDB 提供原生 C/C++ API，可将 ClickHouse 功能直接嵌入应用程序。该 API 既支持简单查询，也支持持久连接、流式返回查询结果等高级功能。

<div id="installation">
  ## 安装
</div>

<div id="install-libchdb">
  ### 第 1 步：安装 libchdb
</div>

在系统上安装 chDB 库：

```bash theme={null}
curl -sL https://lib.chdb.io | bash
```

<div id="include-headers">
  ### 第 2 步：引入头文件
</div>

在项目中引入 chDB 头文件：

```c theme={null}
#include <chdb.h>
```

<div id="link-library">
  ### 第 3 步：链接库文件
</div>

编译应用程序并将其与 chDB 链接：

```bash theme={null}
# C 编译
gcc -o myapp myapp.c -lchdb

# C++ 编译  
g++ -o myapp myapp.cpp -lchdb
```

<div id="c-examples">
  ## C 示例
</div>

<div id="basic-connection-queries">
  ### 基本连接与查询
</div>

```c theme={null}
#include <stdio.h>
#include <chdb.h>

int main() {
    // 创建连接参数
    char* args[] = {"chdb", "--path", "/tmp/chdb-data"};
    int argc = 3;
    
    // 连接到 chDB
    chdb_connection* conn = chdb_connect(argc, args);
    if (!conn) {
        printf("Failed to connect to chDB\n");
        return 1;
    }
    
    // 执行查询
    chdb_result* result = chdb_query(*conn, "SELECT version()", "CSV");
    if (!result) {
        printf("Query execution failed\n");
        chdb_close_conn(conn);
        return 1;
    }
    
    // 检查错误
    const char* error = chdb_result_error(result);
    if (error) {
        printf("Query error: %s\n", error);
    } else {
        // 获取结果数据
        char* data = chdb_result_buffer(result);
        size_t length = chdb_result_length(result);
        double elapsed = chdb_result_elapsed(result);
        uint64_t rows = chdb_result_rows_read(result);
        
        printf("Result: %.*s\n", (int)length, data);
        printf("Elapsed: %.3f seconds\n", elapsed);
        printf("Rows: %llu\n", rows);
    }
    
    // 清理资源
    chdb_destroy_query_result(result);
    chdb_close_conn(conn);
    return 0;
}
```

<div id="streaming-queries">
  ### 流式查询
</div>

```c theme={null}
#include <stdio.h>
#include <chdb.h>

int main() {
    char* args[] = {"chdb", "--path", "/tmp/chdb-stream"};
    chdb_connection* conn = chdb_connect(3, args);
    
    if (!conn) {
        printf("Failed to connect\n");
        return 1;
    }
    
    // 开始流式查询
    chdb_result* stream_result = chdb_stream_query(*conn, 
        "SELECT number FROM system.numbers LIMIT 1000000", "CSV");
    
    if (!stream_result) {
        printf("Failed to start streaming query\n");
        chdb_close_conn(conn);
        return 1;
    }
    
    uint64_t total_rows = 0;
    
    // 处理数据块
    while (true) {
        chdb_result* chunk = chdb_stream_fetch_result(*conn, stream_result);
        if (!chunk) break;
        
        // 检查此数据块中是否有数据
        size_t chunk_length = chdb_result_length(chunk);
        if (chunk_length == 0) {
            chdb_destroy_query_result(chunk);
            break; // 流结束
        }
        
        uint64_t chunk_rows = chdb_result_rows_read(chunk);
        total_rows += chunk_rows;
        
        printf("Processed chunk: %llu rows, %zu bytes\n", chunk_rows, chunk_length);
        
        // 在此处理数据块内容
        // char* data = chdb_result_buffer(chunk);
        
        chdb_destroy_query_result(chunk);
        
        // 进度上报
        if (total_rows % 100000 == 0) {
            printf("Progress: %llu rows processed\n", total_rows);
        }
    }
    
    printf("Streaming complete. Total rows: %llu\n", total_rows);
    
    // 清理流式查询资源
    chdb_destroy_query_result(stream_result);
    chdb_close_conn(conn);
    return 0;
}
```

<div id="data-formats">
  ### 使用不同数据格式
</div>

```c theme={null}
#include <stdio.h>
#include <chdb.h>

int main() {
    char* args[] = {"chdb"};
    chdb_connection* conn = chdb_connect(1, args);
    
    const char* query = "SELECT number, toString(number) as str FROM system.numbers LIMIT 3";
    
    // CSV 格式
    chdb_result* csv_result = chdb_query(*conn, query, "CSV");
    printf("CSV Result:\n%.*s\n\n", 
           (int)chdb_result_length(csv_result), 
           chdb_result_buffer(csv_result));
    chdb_destroy_query_result(csv_result);
    
    // JSON 格式
    chdb_result* json_result = chdb_query(*conn, query, "JSON");
    printf("JSON Result:\n%.*s\n\n", 
           (int)chdb_result_length(json_result), 
           chdb_result_buffer(json_result));
    chdb_destroy_query_result(json_result);
    
    // Pretty 格式
    chdb_result* pretty_result = chdb_query(*conn, query, "Pretty");
    printf("Pretty Result:\n%.*s\n\n", 
           (int)chdb_result_length(pretty_result), 
           chdb_result_buffer(pretty_result));
    chdb_destroy_query_result(pretty_result);
    
    chdb_close_conn(conn);
    return 0;
}
```

<div id="cpp-example">
  ## C++ 示例
</div>

```cpp theme={null}
#include <iostream>
#include <string>
#include <vector>
#include <chdb.h>

class ChDBConnection {
private:
    chdb_connection* conn;
    
public:
    ChDBConnection(const std::vector<std::string>& args) {
        // 将字符串向量转换为 char* 数组
        std::vector<char*> argv;
        for (const auto& arg : args) {
            argv.push_back(const_cast<char*>(arg.c_str()));
        }
        
        conn = chdb_connect(argv.size(), argv.data());
        if (!conn) {
            throw std::runtime_error("Failed to connect to chDB");
        }
    }
    
    ~ChDBConnection() {
        if (conn) {
            chdb_close_conn(conn);
        }
    }
    
    std::string query(const std::string& sql, const std::string& format = "CSV") {
        chdb_result* result = chdb_query(*conn, sql.c_str(), format.c_str());
        if (!result) {
            throw std::runtime_error("Query execution failed");
        }
        
        const char* error = chdb_result_error(result);
        if (error) {
            std::string error_msg(error);
            chdb_destroy_query_result(result);
            throw std::runtime_error("Query error: " + error_msg);
        }
        
        std::string data(chdb_result_buffer(result), chdb_result_length(result));
        
        // 获取查询的统计信息
        std::cout << "Query statistics:\n";
        std::cout << "  Elapsed: " << chdb_result_elapsed(result) << " seconds\n";
        std::cout << "  Rows read: " << chdb_result_rows_read(result) << "\n";
        std::cout << "  Bytes read: " << chdb_result_bytes_read(result) << "\n";
        
        chdb_destroy_query_result(result);
        return data;
    }
};

int main() {
    try {
        // 创建连接
        ChDBConnection db({{"chdb", "--path", "/tmp/chdb-cpp"}});
        
        // 创建表并插入数据
        db.query("CREATE TABLE test (id UInt32, value String) ENGINE = MergeTree() ORDER BY id");
        db.query("INSERT INTO test VALUES (1, 'hello'), (2, 'world'), (3, 'chdb')");
        
        // 使用不同格式查询
        std::cout << "CSV Results:\n" << db.query("SELECT * FROM test", "CSV") << "\n";
        std::cout << "JSON Results:\n" << db.query("SELECT * FROM test", "JSON") << "\n";
        
        // 聚合查询
        std::cout << "Count: " << db.query("SELECT COUNT(*) FROM test") << "\n";
        
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}
```

<div id="error-handling">
  ## 错误处理最佳实践
</div>

```c theme={null}
#include <stdio.h>
#include <chdb.h>

int safe_query_example() {
    chdb_connection* conn = NULL;
    chdb_result* result = NULL;
    int return_code = 0;
    
    // 创建连接
    char* args[] = {"chdb"};
    conn = chdb_connect(1, args);
    if (!conn) {
        printf("Failed to create connection\n");
        return 1;
    }
    
    // 执行查询
    result = chdb_query(*conn, "SELECT invalid_syntax", "CSV");
    if (!result) {
        printf("Query execution failed\n");
        return_code = 1;
        goto cleanup;
    }
    
    // 检查查询错误
    const char* error = chdb_result_error(result);
    if (error) {
        printf("Query error: %s\n", error);
        return_code = 1;
        goto cleanup;
    }
    
    // 处理成功的结果
    printf("Result: %.*s\n", 
           (int)chdb_result_length(result), 
           chdb_result_buffer(result));
    
cleanup:
    if (result) chdb_destroy_query_result(result);
    if (conn) chdb_close_conn(conn);
    return return_code;
}
```

<div id="github-repository">
  ## GitHub 仓库
</div>

* **主仓库**: [chdb-io/chdb](https://github.com/chdb-io/chdb)
* **问题与支持**: 请在 [GitHub 仓库](https://github.com/chdb-io/chdb/issues) 中报告问题
* **C API 文档**: [Bindings 文档](https://github.com/chdb-io/chdb/blob/main/bindings.md)
