C語言操作MySQL出現“Commands out of sync”錯誤:如何解決并發問題?

C語言操作MySQL出現“Commands out of sync”錯誤:如何解決并發問題?

c語言操作mysql遇到“[2014]: commands out of sync; you can’t run this command now”問題

問題詳情:

c語言操作mysql時,遇到了如題所述的錯誤。該錯誤導致后續的所有sql命令都無法執行。問題可以通過快速執行多次前端操作來觸發。

錯誤日志示例:

立即學習C語言免費學習筆記(深入)”;

23-05-05 11:30:20 | info | mysqlquery.success | sql: select * from tb_video where id='0105a290'; 23-05-05 11:30:20 | error | video selectone | mysql store result failed | err[0]: 23-05-05 11:30:20 | error | mysqlquery.err | sql: select * from tb_video where id='6d1db3db'; 23-05-05 11:30:27 | error | mysqlquery.err | err[2014]: commands out of sync; you can't run this command now

解決方法:

從日志上看,問題出現在 updatevideoview 函數中,在執行 select 語句后又進行了 update 操作。這導致了并發問題,使得后續的 select 語句無法正常執行。

為了解決該問題,需要在 updatevideoview 函數中添加如下鎖:

void UpdateVideoView(std::string id) {   std::lock_guard<std::mutex> lock(_mutex);   MysqlQuery query;   if (!query.Query("UPDATE tb_views SET view=view+1 WHERE id='%s'", id.c_str())) {     return;   } }

通過添加鎖,可以確保在執行 update 語句之前,沒有其他線程正在執行 select 語句,從而避免了并發問題。

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享