操作存儲過程連接代碼
錯誤代碼:
Commands out of sync; you can't run this command now
DB_Param mDB("192.168.1.254", "admin", "admin", "node", 3306, NULL, CLIENT_MULTI_STATEMENTS );//CLIENT_MULTI_RESULTS);
CMysql mysql(mDB);
bool CMysql::ConnectDB(DB_Param* p)
{
if(!mysql_real_connect(&mysql,(p->mStrHost).c_str(),p->mStrUser.c_str(),p->mStrPassword.c_str(),p->mStrDB.c_str(),p->mIPort,p->unix_socket,p->client_flag))
{
return false;
}
return true;
}
上面的最後一個參數,需要使用
CLIENT_MULTI_STATEMENTS )或者CLIENT_MULTI_RESULTS)
C++操作MySQL存儲過程中,出現如下錯誤
Commands out of sync; you can't run this command now
原因應該是MYSQL_RES 結果在下一次查詢的時候沒有被釋放掉,所以出現該錯誤
官方解釋如下:
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));
上面的代碼在我的程序中沒有成功。我的解決方法:兩種
第一種方法:調用一次查詢函數,釋放一次,做到每一次操作數據庫,都重新連接一次數據庫,用完該次操作立刻釋放掉MYSQL_RES結果集
該方法,操作數據庫頻繁,效率相對不高
第二種方法:將所有的數據讀到緩存中,對緩存進行讀寫,效率較高,空間換時間的一種做法。
兩種方法都有各自的解決方法,取決於你的程序的實際情況。