ZBLOG

C通过haproxy连接tidb示例

以下是一个使用C通过HAProxy连接TiDB的示例代码:

#include <stdio.h>
#include <mysql/mysql.h>

int main() {
    MYSQL *con = mysql_init(NULL);

    // 建立与HAProxy的连接
    if (mysql_real_connect(con, "haproxy_ip", "username", "password", NULL, 0, NULL, 0) == NULL) {
        fprintf(stderr, "Failed to connect to HAProxy: %s\n", mysql_error(con));
        return 1;
    }

    // 选择要连接的数据库
    if (mysql_query(con, "USE database_name")) {
        fprintf(stderr, "Failed to select database: %s\n", mysql_error(con));
        return 1;
    }

    // 执行SQL查询
    if (mysql_query(con, "SELECT * FROM table_name")) {
        fprintf(stderr, "Failed to execute query: %s\n", mysql_error(con));
        return 1;
    }
    
    MYSQL_RES *result = mysql_store_result(con);
  
    if (result == NULL) {
        fprintf(stderr, "Failed to get result set: %s\n", mysql_error(con));
        return 1;
    }

    int num_fields = mysql_num_fields(result);
  
    MYSQL_ROW row;
  
     // 处理查询结果
     while ((row = mysql_fetch_row(result))) {
         for(int i = 0; i < num_fields; i++) {
             printf("%s ", row[i] ? row[i] : "NULL");
         }
         printf("\n");
     }
     
     mysql_free_result(result);
     
     // 关闭数据库连接
     mysql_close(con);

     return 0;
}

在上面的示例中,你需要将haproxy_ip替换为实际的HAProxy服务器IP地址,usernamepassword替换为用于连接TiDB的凭据信息。然后,你可以根据需要修改数据库名称、表名和SQL查询语句。

请注意,此示例使用了MySQL C API来连接和操作TiDB数据库。你需要在编译时确保链接了MySQL C库,并且包含了相关头文件。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=11241

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?