前兩天搞mysql的東西,用mysql提供的C API 訪問,遇到些問題,在這里分享一下,希望對其他人有幫助。
用mysql C API 調用存儲過程,并返回結果集。需要注意幾個問題:
在建立鏈接的時候要加選項CLIENT_MULTI_STATEMENTS 或 CLIENT_MULTI_RESULTS,以便可以讓query執行多個語句。
mysql_real_connect(mySQL,serverIP,user,password,database,serverPort,NULL,CLIENT_MULTI_STATEMENTS)
當query時可能產生錯誤error:2014 Commands out of sync; you can't run this command now
Mysql文檔中說明錯誤:Commands out of sync
If you get Commands out of sync; you can't run this command now in your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and try to execute a new query before you have called mysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() or mysql_store_result() in between.
當執行完query后,mysql將結果集放在一個result集中,產生以上問題的原因有兩個:
一是未將MYSQL_RES所指對象釋放,即在下次查詢時要mysql_free_result();
二是結果result集不為空,這個原因比較隱蔽。解決方法可以用如下寫法:
do
{
/* Process all results */
printf("total affected rows: %lld", mysql_affected_rows(mysql));

if (!(result= mysql_store_result(mysql)))
{
printf(stderr, "Got fatal error processing query/n");
exit(1);
}
process_result_set(result); /* client function */
mysql_free_result(result);
} while (!mysql_next_result(mysql)); 還有個問題感覺比較奇怪,我調用一個存儲過程,存儲過程中就一句select
Create procedure test()
Begin
Select * from test ;
End ;
用以上方法處理結果集循環會執行兩次,開始我只調了一次result= mysql_store_result(mysql)),導致以后執行query報2014錯誤。