Welcome

首页 / 数据库 / MySQL / 在MySQL数据库中使用C执行SQL语句(3)

在MySQL数据库中使用C执行SQL语句(3)2007-04-27 ccidnet.com 检索数据

现在开始编写从数据库中检索数据的第一个程序。我们将选择所有年龄大于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 ");
            res = mysql_query(&my_connection, "SELECT childno, fname,
            age FROM children WHERE age > 5");
            if (res) {
            printf("SELECT error: %s ", mysql_error(&my_connection));
            } else {
            res_ptr = mysql_store_result(&my_connection);
            if (res_ptr) {
            printf("Retrieved %luows ",(unsignedlong)mysql_num_rows(res_ptr));
            while ((sqlrow = mysql_fetch_row(res_ptr))) {
            printf("Fetched data... ");
            }
            if (mysql_errno(&my_connection)) {
            fprintf(stderr, "Retrive error: s ",mysql_error(&my_connection));
            }
            }
            mysql_free_result(res_ptr);
            }
            mysql_close(&my_connection);
            } else {
            fprintf(stderr, "Connection failed ");
            if (mysql_errno(&my_connection)) {
            fprintf(stderr, "Connection error %d: %s ",
            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相似,它返回指向结果集对象的指针;关键的不同点在于返回时,实际上没有将任何数据检索到结果集,只是初始化结果集以准备好检索数据。

参考资料

您可以参阅本文在developerWorks全球站点上的英文原文.

本文章取自Wrox Press Ltd出版的Professional Linux一书的第5章。

关于作者

Rick Stones是一位系统设计师,他在一家大型泛欧制药分销和分配公司的IT部门工作。从1985年开始,他一直在使用各种形式的 UNIX,并且发现带有早期 .99 CD-ROM发行版的Linux。他用各种语言编写UNIX、Linux和其它平台的软件,同时还安装并管理几台Linux服务器。在非常有限的业余时间,他努力提高他的钢琴演奏技巧。