在MySQL数据库中使用C执行SQL语句
检索数据
现在开始编写从数据库中检索数据的第一个程序。我们将选择所有年龄大于5的行的内容。不幸的是我们还不知道如何处理这个数据,所以我们能做的只有循环检索它。这便是 select1.c:
#include
#include
![]()
#include "mysql.h"
![]()
MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;
![]()
int main(int argc, char *argv[]) ...{
int res;
![]()
mysql_init(&my_connection);
if (mysql_real_connect(&my_connection, "localhost", "rick",
"bar", "rick", 0, NULL, 0)) ...{
printf("Connection success\n");
![]()
res = mysql_query(&my_connection, "SELECT childno, fname,
age FROM children WHERE age > 5");
if (res) ...{
printf("SELECT error: %s\n", mysql_error(&my_connection));
} else ...{
res_ptr = mysql_store_result(&my_connection);
if (res_ptr) ...{
printf("Retrieved %luows\n",(unsignedlong)mysql_num_rows(res_ptr));
while ((sqlrow = mysql_fetch_row(res_ptr))) ...{
printf("Fetched data...\n");
}
if (mysql_errno(&my_connection)) ...{
fprintf(stderr, "Retrive error: s\n",mysql_error(&my_connection));
}
}
mysql_free_result(res_ptr);
}
![]()
mysql_close(&my_connection);
![]()
} else ...{
fprintf(stderr, "Connection failed\n");
if (mysql_errno(&my_connection)) ...{
fprintf(stderr, "Connection error %d: %s\n",
mysql_errno(&my_connection),mysql_error(&my_connection));
}
}
![]()
return EXIT_SUCCESS;
}
检索结果集并循环通过已检索的数据的重要部分都已突出显示。
一次检索一行数据
要按需要逐行检索数据,而不是立即获取全部数据并将它存储在客户机中,可以将mysql_store_result调用替换成 mysql_use_result:
MYSQL_RES *mysql_use_result(MYSQL *connection);
这个函数还取得一个连接对象并返回结果结合指针,或者出错时返回NULL。与mysql_store_result相似,它返回指向结果集对象的指针;关键的不同点在于返回时,实际上没有将任何数据检索到结果集,只是初始化结果集以准备好检索数据。
0
相关文章
