---
title: "提高MySQL 查询效率的三个技巧"
author: "mlxia"
date: "2007-11-15T11:06:07Z"
tags: []
slug: "mysql"
draft: false
lastmod: "2009-07-20T14:49:12Z"
id: 140805
url: "https://mlxia.iteye.com/blog/140805"
---

MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试. 1. 使用statement进行绑定查询 2. 随机的获取记录 3. 使用连接池管理连接.

 

 

MySQL由于它本身的小巧和操作的高效, 在数据库应用中越来越多的被采用.我在开发一个P2P应用的时候曾经使用MySQL来保存P2P节点,由于P2P的应用中,结点数动辄上万个,而且节点变化频繁,因此一定要保持查询和插入的高效.以下是我在使用过程中做的提高效率的三个有效的尝试.

 

l        使用statement进行绑定查询

使用statement可以提前构建查询语法树,在查询时不再需要构建语法树就直接查询.因此可以很好的提高查询的效率. 这个方法适合于查询条件固定但查询非常频繁的场合.

使用方法是:

1. 绑定, 创建一个MYSQL\_STMT变量,与对应的查询字符串绑定,字符串中的问号代表要传入的变量,每个问号都必须指定一个变量.
2. 查询, 输入每个指定的变量, 传入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-&gt;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-&gt;channelid;

       insertbind\[1].is\_null = 0;

       insertbind\[1].length = 0;

 

       insertbind\[2].buffer\_type = MYSQL\_TYPE\_TINY;

       insertbind\[2].buffer = (char \*)&m\_stInsertParam-&gt;ISPtype;

       insertbind\[2].is\_null = 0;

       insertbind\[2].length = 0;

 

       insertbind\[3].buffer\_type = MYSQL\_TYPE\_LONG;

       insertbind\[3].buffer = (char \*)&m\_stInsertParam-&gt;externalIP;

       insertbind\[3].is\_null = 0;

       insertbind\[3].length = 0;

      

       insertbind\[4].buffer\_type = MYSQL\_TYPE\_SHORT;

       insertbind\[4].buffer = (char \*)&m\_stInsertParam-&gt;externalPort;

       insertbind\[4].is\_null = 0;

       insertbind\[4].length = 0;

 

       insertbind\[5].buffer\_type = MYSQL\_TYPE\_LONG;

       insertbind\[5].buffer = (char \*)&m\_stInsertParam-&gt;internalIP;

       insertbind\[5].is\_null = 0;

       insertbind\[5].length = 0;

 

       insertbind\[6].buffer\_type = MYSQL\_TYPE\_SHORT;

       insertbind\[6].buffer = (char \*)&m\_stInsertParam-&gt;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-&gt;sessionid, sessionid);

       strcpy(m\_stInsertParam-&gt;channelid, channelid);

       m\_stInsertParam-&gt;ISPtype = ISPtype;

       m\_stInsertParam-&gt;externalIP = eIP;

       m\_stInsertParam-&gt;externalPort = eport;

       m\_stInsertParam-&gt;internalIP = iIP;

       m\_stInsertParam-&gt;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));      ///&lt;所有的搜索结果数

       //计算待返回的结果数

       int iReturnNumRows = (iAllNumRows &lt;= RETURN\_QUERY\_HOST\_NUM)? iAllNumRows:RETURN\_QUERY\_HOST\_NUM;

       if(iReturnNumRows &lt;= RETURN\_QUERY\_HOST\_NUM)

       {

              //获取逐条记录

              for(int i = 0; i&lt;iReturnNumRows; 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;    ///&lt;余数

              int iQuotient = iAllNumRows/iReturnNumRows;      ///&lt;商

              int iStartIndex = rand()%(iRemainder + 1);         ///&lt;开始下标 

              //获取逐条记录

        for(int iSelectedIndex = 0; iSelectedIndex &lt; iReturnNumRows; 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 &lt;= RETURN\_QUERY\_HOST\_NUM)?

              0:(rand()%(iAllNumRows - RETURN\_QUERY\_HOST\_NUM));

       int iLimitUpper = (iAllNumRows &lt;= RETURN\_QUERY\_HOST\_NUM)?

              iAllNumRows:(iLimitLower + RETURN\_QUERY\_HOST\_NUM);

       //计算待返回的结果数

       int iReturnNumRows = (iAllNumRows &lt;= 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&lt;iReturnNumRows; 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&lt;MYSQL \*&gt; CONNECTION\_HANDLE\_LIST;

typedef std::list&lt;MYSQL \*&gt;::iterator CONNECTION\_HANDLE\_LIST\_IT;

 

//连接数据库的参数结构

class CDBParameter            

{

public:

       char \*host;                                 ///&lt;主机名

       char \*user;                                 ///&lt;用户名

       char \*password;                         ///&lt;密码

       char \*database;                           ///&lt;数据库名

       unsigned int port;                 ///&lt;端口，一般为0

       const char \*unix\_socket;      ///&lt;套接字，一般为NULL

       unsigned int client\_flag; ///&lt;一般为0

};

 

//创建两个队列

CONNECTION\_HANDLE\_LIST m\_lsBusyList;                ///&lt;正在使用的连接句柄

CONNECTION\_HANDLE\_LIST m\_lsIdleList;                  ///&lt;未使用的连接句柄

 

//所有的连接句柄先连上数据库,加入到空闲队列中,等待使用.

bool CDBManager::Connect(char * host /* = "localhost" \*/, char * user /* = "chenmin" \*/, \\

                                           char * password /* = "chenmin" \*/, char * database /* = "HostCache" \*/)

{

       CDBParameter * lpDBParam = new CDBParameter();

       lpDBParam-&gt;host = host;

       lpDBParam-&gt;user = user;

       lpDBParam-&gt;password = password;

       lpDBParam-&gt;database = database;

       lpDBParam-&gt;port = 0;

       lpDBParam-&gt;unix\_socket = NULL;

       lpDBParam-&gt;client\_flag = 0;

       try

       {

              //连接

              for(int index = 0; index &lt; CONNECTION\_NUM; index++)

              {

                     MYSQL * pConnectHandle = mysql\_init((MYSQL\*) 0);     //初始化连接句柄

                     if(!mysql\_real\_connect(pConnectHandle, lpDBParam-&gt;host, lpDBParam-&gt;user, lpDBParam-&gt;password,\\

       lpDBParam-&gt;database,lpDBParam-&gt;port,lpDBParam-&gt;unix\_socket,lpDBParam-&gt;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;

}