有關Mysql的mysql_store_result函數返回NULL的情況以及其他注意事項


成功調用mysql_query()后,mysql_store_result()能夠返回NULL。出現該情況時,表明出現了下述條件之一:

·         出現了malloc()故障(例如,如果結果集過大)。

·         無法讀取數據(在連接上出現了錯誤)。

·         查詢未返回數據(例如,它是INSERT、UPDATE或DELETE)。

通過調用mysql_field_count(),始終能檢查語句是否應生成非空結果。如果mysql_field_count()返回0,結果為空,而且上一個查詢是未返回值的語句(例如INSERT或DELETE)。如果mysql_field_count()返回非0值,語句應生成非空結果。關於這方面的示例,請參見mysql_field_count()函數介紹:

返回作用在連接上的最近查詢的列數。該函數的正常使用是在mysql_store_result()返回NULL(因而沒有結果集指針)時。在這種情況下,可調用mysql_field_count()來判定mysql_store_result()是否應生成非空結果。這樣,客戶端就能采取恰當的動作,而無需知道查詢是否是SELECT(或類似SELECT的)語句。在這里給出的示例中,演示了完成它的方法。返回表示結果集中列數的無符號整數。

另一種可選的方法是,用mysql_errno(&mysql)替換mysql_field_count(&mysql)調用。在該情況下,無論語句是否是SELECT,你將直接從mysql_store_result()查找錯誤,而不是從mysql_field_count()的值進行推斷。

通過調用mysql_error()或mysql_errno(),可測試是否出現了錯誤。

 

注意:

對於成功調用mysql_query()進行select語句的查詢,即使查詢的數據不存在(即rowcount=0),result也不為NULL。result為NULL的情況只是檢測上一個查詢是否是有返回值的語句。

 

范例:

 1     MYSQL_RES *result;
 2     unsigned int num_fields;
 3     unsigned int num_rows;
 4     if (mysql_query(&mysql, query_string))
 5     {
 6         // error
 7     }
 8     else // query succeeded, process any data returned by it
 9     {
10         result = mysql_store_result(&mysql);
11         if (result) // there are rows
12         {
13             num_fields = mysql_num_fields(result);
14             // retrieve rows, then call mysql_free_result(result)
15         }
16         else // mysql_store_result() returned nothing; should it have?
17         {
18             if (mysql_field_count(&mysql) == 0)
19             {
20                 // query does not return data
21                 // (it was not a SELECT)
22                 num_rows = mysql_affected_rows(&mysql);
23             }
24             else // mysql_store_result() should have returned data
25             {
26                 fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
27             }
28         }
29     }

 

 轉載請注明地址:http://www.cnblogs.com/fnlingnzb-learner/p/5826533.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM