共計 2330 個字符,預計需要花費 6 分鐘才能閱讀完成。
本篇內容介紹了“怎么提高 MySQL 查詢效率”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓丸趣 TV 小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
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- 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;
}
“怎么提高 MySQL 查詢效率”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注丸趣 TV 網站,丸趣 TV 小編將為大家輸出更多高質量的實用文章!