#include <mysql/mysql.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "your_password"; /* set me first */
char *database = "test";
conn = mysql_init(NULL);
/* Connect to database */
if (mysql_real_connect(conn, server, user, password, database, 0, NULL, 0) == NULL) {
fprintf(stderr, "%s\n", mysql_error(conn));
return EXIT_FAILURE;
}
/* Send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
return EXIT_FAILURE;
}
res = mysql_use_result(conn);
/* Output table names from result set */
printf("MySQL Tables in %s database:\n", database);
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
return EXIT_SUCCESS;
}
#include <mysql/mysql.h>
引入了 MySQL C API 的库,使我们可以使用 MySQL 相关的函数。mysql_init(NULL)
初始化了一个 MySQL 连接对象。mysql_real_connect
函数用于建立与 MySQL 数据库的连接。如果连接失败,程序会输出错误信息并退出。mysql_query
函数发送 SQL 查询到数据库。这里我们查询了当前数据库中的所有表。mysql_use_result
获取查询的结果集。mysql_fetch_row
逐行读取结果集,并打印出每个表的名字。mysql_free_result
和 mysql_close
分别用于释放结果集和关闭数据库连接。这个示例展示了如何使用 libmysqlclient
库连接 MySQL 数据库、执行查询并处理结果。请确保在编译时链接 MySQL 客户端库,例如使用 -lmysqlclient
标志。
上一篇:mysql 包含函数
下一篇:mysql数值转字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站