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

前言

最近的项目在使用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()
···
···
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值