热门标签 | HotTags
当前位置:  开发笔记 > 后端 > 正文

提高MySQL数据库查询效率的几个技巧_MySQL

提高MySQL数据库查询效率的几个技巧
MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试.l 使用statement进行绑定查询
使用statement可以提前构建查询语法树,在查询时不再需要构建语法树就直接查询.因此可以很好的提高查询的效率. 这个方法适合于查询条件固定但查询非常频繁的场合.
使用方法是:
绑定, 创建一个MYSQL_STMT变量,与对应的查询字符串绑定,字符串中的问号代表要传入的变量,每个问号都必须指定一个变量.
查询, 输入每个指定的变量, 传入MYSQL_STMT变量用可用的连接句柄执行.
代码如下://1.绑定
bool CDBManager::BindInsertStmt(MYSQL * connecthandle)
{
//作插入操作的绑定
MYSQL_BIND insertbind[FEILD_NUM];
if(m_stInsertParam == NULL)
m_stInsertParam = new CHostCacheTable;
m_stInsertStmt = mysql_stmt_init(connecthandle);
//构建绑定字符串
char insertSQL[SQL_LENGTH];
strcpy(insertSQL, "insert into HostCache(SessionID, ChannelID, ISPType, "
"ExternalIP, ExternalPort, InternalIP, InternalPort) "
"values(?, ?, ?, ?, ?, ?, ?)");
mysql_stmt_prepare(m_stInsertStmt, insertSQL, strlen(insertSQL));
int param_count= mysql_stmt_param_count(m_stInsertStmt);
if(param_count != FEILD_NUM)
return false;
//填充bind结构数组, m_sInsertParam是这个statement关联的结构变量
memset(insertbind, 0, sizeof(insertbind));
insertbind[0].buffer_type = MYSQL_TYPE_STRING;
insertbind[0].buffer_length = ID_LENGTH /* -1 */;
insertbind[0].buffer = (char *)m_stInsertParam->sessionid;
insertbind[0].is_null = 0;
insertbind[0].length = 0; insertbind[1].buffer_type = MYSQL_TYPE_STRING;
insertbind[1].buffer_length = ID_LENGTH /* -1 */;
insertbind[1].buffer = (char *)m_stInsertParam->channelid;
insertbind[1].is_null = 0;
insertbind[1].length = 0; insertbind[2].buffer_type = MYSQL_TYPE_TINY;
insertbind[2].buffer = (char *)&m_stInsertParam->ISPtype;
insertbind[2].is_null = 0;
insertbind[2].length = 0; insertbind[3].buffer_type = MYSQL_TYPE_LONG;
insertbind[3].buffer = (char *)&m_stInsertParam->externalIP;
insertbind[3].is_null = 0;
insertbind[3].length = 0;

insertbind[4].buffer_type = MYSQL_TYPE_SHORT;
insertbind[4].buffer = (char *)&m_stInsertParam->externalPort;
insertbind[4].is_null = 0;
insertbind[4].length = 0; insertbind[5].buffer_type = MYSQL_TYPE_LONG;
insertbind[5].buffer = (char *)&m_stInsertParam->internalIP;
insertbind[5].is_null = 0;
insertbind[5].length = 0; insertbind[6].buffer_type = MYSQL_TYPE_SHORT;
insertbind[6].buffer = (char *)&m_stInsertParam->internalPort;
insertbind[6].is_null = 0;
insertbind[6].is_null = 0;
//绑定
if (mysql_stmt_bind_param(m_stInsertStmt, insertbind))
return false;
return true;
}//2.查询
bool CDBManager::InsertHostCache2(MYSQL * connecthandle, char * sessionid, char * channelid, int ISPtype, /
unsigned int eIP, unsigned short eport, unsigned int iIP, unsigned short iport)
{
//填充结构变量m_sInsertParam
strcpy(m_stInsertParam->sessionid, sessionid);
strcpy(m_stInsertParam->channelid, channelid);
m_stInsertParam->ISPtype = ISPtype;
m_stInsertParam->externalIP = eIP;
m_stInsertParam->externalPort = eport;
m_stInsertParam->internalIP = iIP;
m_stInsertParam->internalPort = iport;
//执行statement,性能瓶颈处
if(mysql_stmt_execute(m_stInsertStmt))
return false;
return true;
}l 随机的获取记录
在某些数据库的应用中, 我们并不是要获取所有的满足条件的记录,而只是要随机挑选出满足条件的记录. 这种情况常见于数据业务的统计分析,从大容量数据库中获取小量的数据的场合.
有两种方法可以做到
1. 常规方法,首先查询出所有满足条件的记录,然后随机的挑选出部分记录.这种方法在满足条件的记录数很多时效果不理想.
2. 使用limit语法,先获取满足条件的记录条数, 然后在sql查询语句中加入limit来限制只查询满足要求的一段记录. 这种方法虽然要查询两次,但是在数据量大时反而比较高效.
示例代码如下://1.常规的方法
//性能瓶颈,10万条记录时,执行查询140ms, 获取结果集500ms,其余可忽略
int CDBManager::QueryHostCache(MYSQL* connecthandle, char * channelid, int ISPtype, CDBManager::CHostCacheTable * &hostcache)
{
char selectSQL[SQL_LENGTH];
memset(selectSQL, 0, sizeof(selectSQL));
sprintf(selectSQL,"select * from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0) //检索
return 0;
//获取结果集
m_pResultSet = mysql_store_result(connecthandle);
if(!m_pResultSet) //获取结果集出错
return 0;
int iAllNumRows = (int)(mysql_num_rows(m_pResultSet)); ///<所有的搜索结果数
//计算待返回的结果数
int iReturnNumRows = (iAllNumRows <= RETURN_QUERY_HOST_NUM)? iAllNumRows:RETURN_QUERY_HOST_NUM;
if(iReturnNumRows <= RETURN_QUERY_HOST_NUM)
{
//获取逐条记录
for(int i = 0; i {
//获取逐个字段
m_Row = mysql_fetch_row(m_pResultSet);
if(m_Row[0] != NULL)
strcpy(hostcache[i].sessionid, m_Row[0]);
if(m_Row[1] != NULL)
strcpy(hostcache[i].channelid, m_Row[1]);
if(m_Row[2] != NULL)
hostcache[i].ISPtype = atoi(m_Row[2]);
if(m_Row[3] != NULL)
hostcache[i].externalIP = atoi(m_Row[3]);
if(m_Row[4] != NULL)
hostcache[i].externalPort = atoi(m_Row[4]);
if(m_Row[5] != NULL)
hostcache[i].internalIP = atoi(m_Row[5]);
if(m_Row[6] != NULL)
hostcache[i].internalPort = atoi(m_Row[6]);
}
}
else
{
//随机的挑选指定条记录返回
int iRemainder = iAllNumRows%iReturnNumRows; ///<余数
int iQuotient = iAllNumRows/iReturnNumRows; ///<商
int iStartIndex = rand()%(iRemainder + 1); ///<开始下标
//获取逐条记录
for(int iSelectedIndex = 0; iSelectedIndex {
mysql_data_seek(m_pResultSet, iStartIndex + iQuotient * iSelectedIndex);
m_Row = mysql_fetch_row(m_pResultSet);
if(m_Row[0] != NULL)
strcpy(hostcache[iSelectedIndex].sessionid, m_Row[0]);
if(m_Row[1] != NULL)
strcpy(hostcache[iSelectedIndex].channelid, m_Row[1]);
if(m_Row[2] != NULL)
hostcache[iSelectedIndex].ISPtype = atoi(m_Row[2]);
if(m_Row[3] != NULL)
hostcache[iSelectedIndex].externalIP = atoi(m_Row[3]);
if(m_Row[4] != NULL)
hostcache[iSelectedIndex].externalPort = atoi(m_Row[4]);
if(m_Row[5] != NULL)
hostcache[iSelectedIndex].internalIP = atoi(m_Row[5]);
if(m_Row[6] != NULL)
hostcache[iSelectedIndex].internalPort = atoi(m_Row[6]);
}
}
//释放结果集内容
mysql_free_result(m_pResultSet);
return iReturnNumRows;
}//2.使用limit版
int CDBManager::QueryHostCache(MYSQL * connecthandle, char * channelid, unsigned int myexternalip, int ISPtype, CHostCacheTable * hostcache)
{
//首先获取满足结果的记录条数,再使用limit随机选择指定条记录返回
MYSQL_ROW row;
MYSQL_RES * pResultSet;
char selectSQL[SQL_LENGTH];
memset(selectSQL, 0, sizeof(selectSQL)); sprintf(selectSQL,"select count(*) from HostCache where ChannelID = '%s' and ISPtype = %d", channelid, ISPtype);
if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0) //检索
return 0;
pResultSet = mysql_store_result(connecthandle);
if(!pResultSet)
return 0;
row = mysql_fetch_row(pResultSet);
int iAllNumRows = atoi(row[0]);
mysql_free_result(pResultSet);
//计算待取记录的上下范围
int iLimitLower = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
0:(rand()%(iAllNumRows - RETURN_QUERY_HOST_NUM));
int iLimitUpper = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
iAllNumRows:(iLimitLower + RETURN_QUERY_HOST_NUM);
//计算待返回的结果数
int iReturnNumRows = (iAllNumRows <= RETURN_QUERY_HOST_NUM)?
iAllNumRows:RETURN_QUERY_HOST_NUM;

//使用limit作查询
sprintf(selectSQL,"select SessionID, ExternalIP, ExternalPort, InternalIP, InternalPort "
"from HostCache where ChannelID = '%s' and ISPtype = %d limit %d, %d"
, channelid, ISPtype, iLimitLower, iLimitUpper);
if(mysql_real_query(connecthandle, selectSQL, strlen(selectSQL)) != 0) //检索
return 0;
pResultSet = mysql_store_result(connecthandle);
if(!pResultSet)
return 0;
//获取逐条记录
for(int i = 0; i {
//获取逐个字段
row = mysql_fetch_row(pResultSet);
if(row[0] != NULL)
strcpy(hostcache[i].sessionid, row[0]);
if(row[1] != NULL)
hostcache[i].externalIP = atoi(row[1]);
if(row[2] != NULL)
hostcache[i].externalPort = atoi(row[2]);
if(row[3] != NULL)
hostcache[i].internalIP = atoi(row[3]);
if(row[4] != NULL)
hostcache[i].internalPort = atoi(row[4]);
}
//释放结果集内容
mysql_free_result(pResultSet);
return iReturnNumRows;
}l 使用连接池管理连接.
在有大量节点访问的数据库设计中,经常要使用到连接池来管理所有的连接.
一般方法是:建立两个连接句柄队列,空闲的等待使用的队列和正在使用的队列.
当要查询时先从空闲队列中获取一个句柄,插入到正在使用的队列,再用这个句柄做数据库操作,完毕后一定要从使用队列中删除,再插入到空闲队列.
设计代码如下://定义句柄队列
typedef std::list CONNECTION_HANDLE_LIST;
typedef std::list::iterator CONNECTION_HANDLE_LIST_IT;//连接数据库的参数结构
class CDBParameter
{
public:
char *host; ///<主机名
char *user; ///<用户名
char *password; ///<密码
char *database; ///<数据库名
unsigned int port; ///<端口,一般为0
const char *unix_socket; ///<套接字,一般为NULL
unsigned int client_flag; ///<一般为0
};//创建两个队列
CONNECTION_HANDLE_LIST m_lsBusyList; ///<正在使用的连接句柄
CONNECTION_HANDLE_LIST m_lsIdleList; ///<未使用的连接句柄//所有的连接句柄先连上数据库,加入到空闲队列中,等待使用.
bool CDBManager::Connect(char * host /* = "localhost" */, char * user /* = "chenmin" */, /
char * password /* = "chenmin" */, char * database /* = "HostCache" */)
{
CDBParameter * lpDBParam = new CDBParameter();
lpDBParam->host = host;
lpDBParam->user = user;
lpDBParam->password = password;
lpDBParam->database = database;
lpDBParam->port = 0;
lpDBParam->unix_socket = NULL;
lpDBParam->client_flag = 0;
try
{
//连接
for(int index = 0; index {
MYSQL * pCOnnectHandle= mysql_init((MYSQL*) 0); //初始化连接句柄
if(!mysql_real_connect(pConnectHandle, lpDBParam->host, lpDBParam->user, lpDBParam->password,/
lpDBParam->database,lpDBParam->port,lpDBParam->unix_socket,lpDBParam->client_fla))
return false;
//加入到空闲队列中
m_lsIdleList.push_back(pConnectHandle);
}
}
catch(...)
{
return false;
}
return true;
}//提取一个空闲句柄供使用
MYSQL * CDBManager::GetIdleConnectHandle()
{
MYSQL * pCOnnectHandle= NULL;
m_ListMutex.acquire();
if(m_lsIdleList.size())
{
pCOnnectHandle= m_lsIdleList.front();
m_lsIdleList.pop_front();
m_lsBusyList.push_back(pConnectHandle);
}
else //特殊情况,闲队列中为空,返回为空
{
pCOnnectHandle= 0;
}
m_ListMutex.release(); return pConnectHandle;
}//从使用队列中释放一个使用完毕的句柄,插入到空闲队列
void CDBManager::SetIdleConnectHandle(MYSQL * connecthandle)
{
m_ListMutex.acquire();
m_lsBusyList.remove(connecthandle);
m_lsIdleList.push_back(connecthandle);
m_ListMutex.release();
}
//使用示例,首先获取空闲句柄,利用这个句柄做真正的操作,然后再插回到空闲队列
bool CDBManager::DeleteHostCacheBySessionID(char * sessionid)
{
MYSQL * pCOnnectHandle= GetIdleConnectHandle();
if(!pConnectHandle)
return 0;
bool bRet = DeleteHostCacheBySessionID(pConnectHandle, sessionid);
SetIdleConnectHandle(pConnectHandle);
return bRet;
}
//传入空闲的句柄,做真正的删除操作
bool CDBManager::DeleteHostCacheBySessionID(MYSQL * connecthandle, char * sessionid)
{
char deleteSQL[SQL_LENGTH];
memset(deleteSQL, 0, sizeof(deleteSQL));
sprintf(deleteSQL,"delete from HostCache where SessiOnID= '%s'", sessionid);
if(mysql_query(connecthandle,deleteSQL) != 0) //删除
return false;
return true;
}
推荐阅读
  • 推荐一个ASP的内容管理框架(ASP Nuke)的优势和适用场景
    本文推荐了一个ASP的内容管理框架ASP Nuke,并介绍了其主要功能和特点。ASP Nuke支持文章新闻管理、投票、论坛等主要内容,并可以自定义模块。最新版本为0.8,虽然目前仍处于Alpha状态,但作者表示会继续更新完善。文章还分析了使用ASP的原因,包括ASP相对较小、易于部署和较简单等优势,适用于建立门户、网站的组织和小公司等场景。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文介绍了如何在MySQL中将零值替换为先前的非零值的方法,包括使用内联查询和更新查询。同时还提供了选择正确值的方法。 ... [详细]
  • 在数据分析工作中,我们通常会遇到这样的问题,一个业务部门由若干业务组构成,需要筛选出每个业务组里业绩前N名的业务员。这其实是一个分组排序的 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • Oracle Database 10g许可授予信息及高级功能详解
    本文介绍了Oracle Database 10g许可授予信息及其中的高级功能,包括数据库优化数据包、SQL访问指导、SQL优化指导、SQL优化集和重组对象。同时提供了详细说明,指导用户在Oracle Database 10g中如何使用这些功能。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文详细介绍了MysqlDump和mysqldump进行全库备份的相关知识,包括备份命令的使用方法、my.cnf配置文件的设置、binlog日志的位置指定、增量恢复的方式以及适用于innodb引擎和myisam引擎的备份方法。对于需要进行数据库备份的用户来说,本文提供了一些有价值的参考内容。 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文介绍了adg架构设置在企业数据治理中的应用。随着信息技术的发展,企业IT系统的快速发展使得数据成为企业业务增长的新动力,但同时也带来了数据冗余、数据难发现、效率低下、资源消耗等问题。本文讨论了企业面临的几类尖锐问题,并提出了解决方案,包括确保库表结构与系统测试版本一致、避免数据冗余、快速定位问题等。此外,本文还探讨了adg架构在大版本升级、上云服务和微服务治理方面的应用。通过本文的介绍,读者可以了解到adg架构设置的重要性及其在企业数据治理中的应用。 ... [详细]
  • 本文介绍了使用postman进行接口测试的方法,以测试用户管理模块为例。首先需要下载并安装postman,然后创建基本的请求并填写用户名密码进行登录测试。接下来可以进行用户查询和新增的测试。在新增时,可以进行异常测试,包括用户名超长和输入特殊字符的情况。通过测试发现后台没有对参数长度和特殊字符进行检查和过滤。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • Java String与StringBuffer的区别及其应用场景
    本文主要介绍了Java中String和StringBuffer的区别,String是不可变的,而StringBuffer是可变的。StringBuffer在进行字符串处理时不生成新的对象,内存使用上要优于String类。因此,在需要频繁对字符串进行修改的情况下,使用StringBuffer更加适合。同时,文章还介绍了String和StringBuffer的应用场景。 ... [详细]
author-avatar
咾爺們
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有