以下是一个使用C语言连接HAProxy并操作TiDB数据库的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>
#define HAPROXY_IP "127.0.0.1"
#define HAPROXY_PORT 3306
int main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
// 初始化MySQL连接
conn = mysql_init(NULL);
if (conn == NULL) {
fprintf(stderr, "Failed to initialize MySQL connection\n");
exit(1);
}
// 连接到HAProxy
if (!mysql_real_connect(conn, HAPROXY_IP, "username", "password", NULL, HAPROXY_PORT, NULL, 0)) {
fprintf(stderr, "Failed to connect to HAProxy: %s\n", mysql_error(conn));
exit(1);
}
// 连接到TiDB
if (mysql_query(conn, "USE dbname")) {
fprintf(stderr, "Failed to select TiDB database: %s\n", mysql_error(conn));
exit(1);
}
// 执行查询语句
if (mysql_query(conn, "SELECT * FROM table_name")) {
fprintf(stderr, "Failed to execute query: %s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
// 输出查询结果
while ((row = mysql_fetch_row(res)) != NULL) {
printf("%s\t%s\t%s\n", row[0], row[1], row[2]);
}
// 释放资源
mysql_free_result(res);
mysql_close(conn);
return 0;
}
在上述代码中,你需要将username和password替换为实际的TiDB数据库的用户名和密码。同时,还需要根据实际情况修改dbname和table_name。
确保你已经安装了MySQL C API库,并在编译时链接它。可以使用以下命令来编译:
gcc -o tidb_example tidb_example.c $(mysql_config --cflags --libs)
运行生成的可执行文件即可连接到HAProxy并操作TiDB数据库。
请注意,上述示例代码仅用于演示目的,实际环境中你可能需要进行更多错误处理和异常情况的检查。
内容由零声教学AI助手提供,问题来源于学员提问




