入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

MySQL 中mysql_query()来判断数据库是否连接中断

创建时间:2017-04-21 投稿人: 浏览次数:1088

最近的项目在使用mysql C API进行数据库操作时,写了一个简易的连接池,因为mysql查询和插入频繁,但是单次查询与插入的时间开销小,每次进行数据库连接时的开销大。于是进程启动时建立了若干个长连接加入到连接池中,不同的查询和插入复用这些长连接即可。但是随之会有一个问题,当进程运行了相当长一段时间后,mysql对象中可能与mysql服务器断开连接,这需要做处理。

在每次一个mysql_query时,获得返回值,通过返回值来判断是否需要重建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  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 <errmsg.h>
···
···
flag<-mysql_query()
if flag=CR_SERVER_LOST or flag=SERVER_GONE_ERROR
        Reconnect()
        mysql_query()
···
···
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。