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() ··· ···
相关文章推荐
- MySQL 中mysql_query()来判断数据库是否连接中断(二)
- mysql 数据库中的三种判断是否包含总结
- 判断mysql指定数据库指定表是否存在的SQL语句
- 通过建立Socket连接来快速判断数据库连接是否正确
- mysql判断指定数据库是否存在?
- C#使用Socket快速判断数据库连接是否正常的方法
- PHP连接数据库步骤以及判断是否有值!
- mysql测试数据库是否连接成功
- PHP 判断mysql_query是否执行成功
- 判断数据库是否连接上
- 判断MySQL连接是否有效
- PHP:判断PHP是否成功连接数据库
- php判断mysql_query是否成功执行
- mysql5.7基础 create database if not exists... 判断数据库是否存在 若不存在则创建
- ThinkPHP3.2.3---mysql+ajax实现长连接,实时监测数据库数据是否更新
- 判断MySql某个数据库是否存在
- 判断数据库时时连接程序,判断是否断开,断开则自动连接
- C++ 连接mysql 数据库,以及query语句
- mysql 数据库中的三种判断是否包含总结
- 判断MySql某个数据库是否存在