linux-mysql-store-result

来源:互联网 发布:mac五笔输入法哪个好 编辑:程序博客网 时间:2024/06/05 15:02
#include <stdlib.h>#include <stdio.h>#include <mysql.h>int main(int argc, char *argv[]){MYSQL my_connection;MYSQL_RES * res_ptr;MYSQL_ROW sqlrow;int ret = -1;const char* host = "localhost";const char* user = "root";const char* password = "!QAZ2wsx";const char* dbname = "rick";mysql_init(&my_connection);MYSQL*  conn_ptr= mysql_real_connect(&my_connection ,host, user, password,dbname,0,NULL,0);if(conn_ptr){ret = mysql_query(&my_connection, "select * from children");if(ret){fprintf(stderr, "select error %d : %s \n", mysql_errno(&my_connection), mysql_error(&my_connection));}else{res_ptr = mysql_store_result(&my_connection);if(res_ptr){#if 1printf("Retrive rows: %lu \n", (unsigned long)mysql_num_rows(res_ptr));while((sqlrow=mysql_fetch_row(res_ptr))){printf("childno: %s, fname: %s, age:%s \n", sqlrow[0], sqlrow[1], sqlrow[2]);}#endif#if 0                int total_fileds =  mysql_num_fields(res_ptr);                printf("Retrive rows: %lu , total_fileds : %d \n", (unsigned long)mysql_num_rows(res_ptr), total_fileds);                                while((sqlrow=mysql_fetch_row(res_ptr))){                    for(int j= 0 ; j < total_fileds;++j){                        printf("%s ",sqlrow[j]);                    }                    printf("\n");                }#endif if(mysql_errno(&my_connection)){fprintf(stderr, "Retrive error %d: %s\n", mysql_errno(&my_connection), 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 0;}

运行:

xx@ubuntu:~/workspace/mysql-test$ g++ -o test-select simple_mysql_select.c -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient
xx@ubuntu:~/workspace/mysql-test$ ./test-select
Retrive rows: 8
childno: 1, fname: tom, age:7
childno: 2, fname: lucy, age:4
childno: 3, fname: Kinder, age:10
childno: 4, fname: Jacy, age:9
childno: 5, fname: John, age:8



0 0
原创粉丝点击