1. 程式人生 > >mysql error:2014 Commands out of sync; you can't run this command now

mysql error:2014 Commands out of sync; you can't run this command now

最近在專案中經常會出現資料庫操作失敗的,日誌丟擲的錯誤的 Commands out of sync; you can't run this command now。但是把具體的這條sql語句放到視覺化工具裡面執行卻並沒有什麼問題。所以sql語句並沒有什麼語法的問題,mysql官方對這個錯誤的解釋是:

 

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 calledmysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() ormysql_store_result() in between.

大概的意思就是說你在使用 mysql_use_result() 之前並沒有呼叫mysql_free_result(),或者是你嘗試執行兩次查詢,但是在兩次查詢的中間你並沒有對返回資料呼叫mysql_use_result() ormysql_store_result()就行處理。

排查了所有的帶結果集的sql操作,也都進行了mysql_free_result。多次定位發現,程式是呼叫了一個多條update語句拼接的一個sql命令。 這條update語句是執行成功了,但是卻導致了後續的所有mysql錯誤都是丟擲Commands out of sync; you can't run this command now

 的錯誤。

在mysql在connect函式中可以指定CLIENT_MULTI_STATEMENTS 選項來一次執行通過分號分割的多條sql語句。通過查閱資料發現對於一次執行多條update(或者insert)這類無結果集的sql操作我們也需要對其進行ysql_free_result,在sql語句執行完後加上下面的程式碼便解決該問題

do 
{ 
    result = mysql_store_result( mysql ); 
    mysql_free_result(result); 
}while( !mysql_next_result( mysql ) );

有點奇怪,為什麼result明明獲取出來是NULL,但還是要執行mysql_free_result操作。希望有明白之人可以講解一下