手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网络编程>Mysql>列表

在MySQL数据库中使用C执行SQL语句

来源:互联网 作者:west263.com 时间:2008-02-23
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!




      #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相似,他返回指向结果集对象的指针;关键的不同点在于返回时,实际上没有将任何数据检索到结果集,只是初始化结果集以准备好检索数据。


文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!