2016-01-06 181 views
0

我用mysql_num_rows這個函數總是0mysql_num_rows總是返回0

返回這是我的代碼:

#include <mysql/mysql.h> 
MYSQL *conn; 
MYSQL_RES *res; 
MYSQL_ROW row; 

conn = mysql_init(NULL); 

if (!mysql_real_connect(conn, "", "", "", "", 0, NULL, 0)) { 
    fprintf(stderr, "%s\n", mysql_error(conn)); 
    exit(1); 
} 

if (mysql_query(conn, "SELECT * FROM TEST")) 
{ 
    printf("MySQL query error : %s\n", mysql_error(conn)); 
    exit(1); 
} 

res = mysql_use_result(conn); 

printf("Rows: %d\n", mysql_num_rows(res)); 

while ((row = mysql_fetch_row(res)) != NULL) 
    printf("Row1: %s | Row2: %s | Row3: %s \n", row[0], row[1], row[2]); 

mysql_free_result(res); 
mysql_close(conn); 

而且這是輸出

Rows: 0 
Row1: 1 | Row2: 127.0.0.1 | Row3: Raspberry 
Row1: 2 | Row2: 127.0.0.1 | Row3: Raspberry 

MySQL客戶端版本:5.5 .44

回答

0

我解決了這一問題與鑄造爲int和了mysql_store_result!

printf("Rows: %d\n", (int)mysql_num_rows(res)); 
1

嘗試顯示while循環之後的記錄數如下

printf("Rows: %d\n", mysql_num_rows(res)); 

while ((row = mysql_fetch_row(res)) != NULL) 
    printf("Row1: %s | Row2: %s | Row3: %s \n", row[0], row[1], row[2]); 

printf("Rows: %d\n", mysql_num_rows(res)); 

按照該documentation,當您使用mysql_use_result,該mysql_num_rows不給你,直到之後,你有處理記錄的適當數量。爲了得到它,你需要使用mysql_store_result

希望這有助於