MySQLでmysql_query()は、データベースが接続されていないかどうかを判断します.

3578 ワード

前言
最近のプロジェクトではmysql C APIを使用してデータベース操作を行う場合、mysqlクエリーと挿入が頻繁であるため、簡単な接続プールが書かれていますが、単一のクエリーと挿入の時間のオーバーヘッドは小さく、データベース接続を行うたびにオーバーヘッドが大きいです.プロセスが開始されると、いくつかの長い接続が接続プールに追加され、異なるクエリーと挿入が多重化されます.しかし、プロセスがかなり長い間実行された後、mysqlオブジェクトでmysqlサーバと接続が切断される可能性があるという問題があります.これは処理する必要があります.
主な考え方
毎回mysql_queryでは,戻り値を取得し,戻り値によりmysql接続の再構築が必要か否かを判断する.
mysqlの公式ドキュメント:

mysql_query()

int mysql_query(MYSQL *mysql, const char *stmt_str)

Description

Executes the SQL statement pointed to by the null-terminated string stmt_str. Normally, the string must consist of a single SQL statement without a terminating semicolon (;) or \g. If multiple-statement execution has been enabled, the string can contain several statements separated by semicolons. See Section 26.8.17, “C API Support for Multiple Statement Execution”.

mysql_query() cannot be used for statements that contain binary data; you must use mysql_real_query() instead. (Binary data may contain the \0 character, which mysql_query() interprets as the end of the statement string.)

If you want to know whether the statement returns a result set, you can use mysql_field_count() to check for this. See Section 26.8.7.22, “mysql_field_count()”.

Return Values

Zero for success. Nonzero if an error occurred.

Errors

CR_COMMANDS_OUT_OF_SYNC

Commands were executed in an improper order.

**CR_SERVER_GONE_ERROR**

The MySQL server has gone away.

**CR_SERVER_LOST**

The connection to the server was lost during the query.

CR_UNKNOWN_ERROR

An unknown error occurred.

だからCR_SEVER_GONE_ERRORとCR_SERVER_LOSTは、接続を再構築する必要があるかどうかを判断する.注意errmsgを含める必要がある.hファイル
プロセス疑似コードの実行:
#include 
···
···
flagif flag=CR_SERVER_LOST or flag=SERVER_GONE_ERROR
        Reconnect()
        mysql_query()
···
···