您的位置:首页 > 产品设计 > UI/UE

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

2017-04-21 15:29 465 查看

前言

最近的项目在使用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 <errmsg.h>
···
···
flag<-mysql_query()
if flag=CR_SERVER_LOST or flag=SERVER_GONE_ERROR
Reconnect()
mysql_query()
···
···
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: