⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mysqlquery.cpp

📁 C++连接一写常用数据库的接口
💻 CPP
📖 第 1 页 / 共 2 页
字号:
   _mysqlCurrentRow(0),   _recordValues(NULL),   _numRecordValues(0),   _fieldInformation(NULL),   _numFieldInformation(0),   _parameters(NULL),   _numParameters(0){}  // MysqlQuery::MysqlQuery//------------------------------------------------------------------------------// MysqlQuery::~MysqlQuery//------------------------------------------------------------------------------MysqlQuery::~MysqlQuery(){      // If there is still a transaction, rollback   if (_isTransaction)      rollback();      //Make sure any stored query results are freed.   if (__mysql_res__ != NULL)   {      mysql_free_result(__mysql_res__);      __mysql_res__ = NULL;   }   // Free any parameters   _freeCollection(BIND_PARAMETERS);      // Free the current field values   _freeCollection(FIELD_VALUES);     // Clear any previouse field information.   _freeCollection(FIELD_INFORMATION);   // Release this connection from the parent connection object.   _parentConnection->releaseQueryConnection(this);}  // MysqlQuery::~MysqlQuery//------------------------------------------------------------------------------// MysqlQuery::clearBindParams//------------------------------------------------------------------------------void MysqlQuery::clearBindParams(){   // Free all the bind parameters.   _freeCollection(BIND_PARAMETERS);   }  // MysqlQuery::clearBindParams//------------------------------------------------------------------------------// MysqlQuery::command//------------------------------------------------------------------------------voidMysqlQuery::command(   const string& sqlStatement){   // Clear any bind parameters as we now have a new query   clearBindParams();      // Call the base query to store a copy of the query.   BaseQuery::command(sqlStatement);   } // MysqlQuery::command//------------------------------------------------------------------------------// MysqlQuery::bindParam//------------------------------------------------------------------------------BaseValue*MysqlQuery::bindParam(   const string& paramName){   // Make sure the name has not already been added. If it has, return the instance to it   for (int i=0; i<_numParameters; i++)      if (strcasecmp(_parameters[i]->bindName.c_str(), paramName.c_str()) == 0)         return _parameters[i];   // Make sure the parameter is present in the quey   if (!_isBindParameterPresent(paramName))   {      string err = "bindParam(): The specified bind parameter, ";      err += paramName;      err += ", is not present in the SQL statement: ";      err += _sqlStatement;            throw BindParameterNotPresent(err);   }         // Add the value to the parameters array.   _numParameters++;   _parameters = (MysqlBindParam**)realloc((void*)_parameters, _numParameters * sizeof(MysqlBindParam*));   _parameters[_numParameters-1] = new MysqlBindParam(paramName);           return _parameters[_numParameters-1];   }  // MysqlQuery::bindParam//------------------------------------------------------------------------------// MysqlQuery::execute//------------------------------------------------------------------------------voidMysqlQuery::execute(){   //Make sure any stored query results are freed.   if (__mysql_res__ != NULL)   {      mysql_free_result(__mysql_res__);      __mysql_res__ = NULL;   }   // Number of rows in the result set is now 0   _mysqlNumRows = 0;   _mysqlCurrentRow = 0;      // Clear any previouse field information.   _freeCollection(FIELD_INFORMATION);    // Free the current field values   _freeCollection(FIELD_VALUES);   // IIF there is transaction support enabled then   //   always make sure there is a transaction that the query is occuring in   if (_parentConnection->_mysqlOptions.mysqlOptTransaction)      if (!_isTransaction)         transBegin();            // Resolve the bind parameters   string resolvedSqlStatement = _mysqlParseBindParameters(_sqlStatement);   // Ping the connection to make sure it is still valid.   _parentConnection->_mysqlPing(_index);   // Execute the query   _parentConnection->_mysqlQuery(_index, resolvedSqlStatement);   // Determine if we have any data or not and get the field structures if we do.   // Using store result. This should change to be configurable from the config file.   __mysql_res__ = mysql_store_result(&_parentConnection->_handles[_index]->__mysql__);   if (__mysql_res__ == NULL)   {      // MySQL returned nothing. Is it an error or a DDL or DML statement.      if (mysql_errno(&_parentConnection->_handles[_index]->__mysql__))        {         string err = "execute(): ";         err += "SQL statement: ";         err += _sqlStatement;         err += ", ";         err += mysql_error(&_parentConnection->_handles[_index]->__mysql__);         throw ErrorQuerying(err);      }      // Nope, its a DDL or DML statement.      _fieldCount = 0;      _eof = true;   }   else   {      // We have data      _fieldCount = mysql_num_fields(__mysql_res__);          // Get the field information for this query.      _mysqlGetFieldsInformation();            // Store the number of rows in the result set.      _mysqlNumRows = mysql_num_rows(__mysql_res__);            if (!_mysqlNumRows)         _eof = true;     // No data in result set      else         _eof = false;   }   }  // MysqlQuery::execute//------------------------------------------------------------------------------// MysqlQuery::next//------------------------------------------------------------------------------voidMysqlQuery::fetchNext(){           // Do nothing if the we have reached the end of file.   if (_eof)      return;      // Get the data. mysql_fetch_row() will advance the cursor and don't need to use mysql_data_seek    // mysql_data_seek slows performance on large result sets :( (Thanks to David Wojtowicz for this)      _mysqlGetResultSetRow();   _mysqlCurrentRow++;      // Check if we are at the end of the result set.   if (_mysqlCurrentRow >= _mysqlNumRows)      _eof = true;}  // MysqlQuery::next//------------------------------------------------------------------------------// MysqlQuery::transBegin//------------------------------------------------------------------------------voidMysqlQuery::transBegin(){   // Only allow transactions if they have been enabled   if (_parentConnection->_mysqlOptions.mysqlOptTransaction)   {      // Transaction support enabled      // Make sure a transaction is not already active      if (_isTransaction)         throw TransactionError("transBegin(): "            "A transaction is already active. Commit or rollback the transaction before creating a new transaction.");            // Ping the connection to make sure it is still valid.      _parentConnection->_mysqlPing(_index);            string query = "BEGIN";      if (mysql_real_query(&_parentConnection->_handles[_index]->__mysql__, query.c_str(), query.length()) != 0)      {         // Something went wrong while trying to execute the sql statement, so throw an exception.         string err = "transBegin(): Unable to start transaction";         err += ", ";         err += mysql_error(&_parentConnection->_handles[_index]->__mysql__);         throw TransactionError(err);      }               	_isTransaction = true;         }   else   {      // Transaction support not enabled      throw NotImplemented("transBegin(): Transaction support is not enabled. Please enable in .ini file with 'mysql_opt_transaction = yes' entry.");   }}  // MysqlQuery::transBegin      //------------------------------------------------------------------------------// MysqlQuery::commit//------------------------------------------------------------------------------voidMysqlQuery::commit(){   // Only allow transactions if they have been enabled   if (_parentConnection->_mysqlOptions.mysqlOptTransaction)   {      // Transaction support enabled      // Make sure a transaction is active      if (!_isTransaction)         throw TransactionError("commit(): "            "A transaction is not active. Create a transaction before calling commit.");      // Ping the connection to make sure it is still valid.      _parentConnection->_mysqlPing(_index);            string query = "COMMIT";      if (mysql_real_query(&_parentConnection->_handles[_index]->__mysql__, query.c_str(), query.length()) != 0)      {         // Something went wrong while trying to execute the sql statement, so throw an exception.         string err = "commit(): Unable to commit the transaction";         err += ", ";         err += mysql_error(&_parentConnection->_handles[_index]->__mysql__);         throw TransactionError(err);      }            _isTransaction = false;   }   else   {      // Transaction support not enabled      throw NotImplemented("commit(): Transaction support is not enabled. Please enable in .ini file with 'mysql_opt_transaction = yes' entry.");   }}  // MysqlQuery::commit      //------------------------------------------------------------------------------// MysqlQuery::rollback//------------------------------------------------------------------------------voidMysqlQuery::rollback(){   // Only allow transactions if they have been enabled   if (_parentConnection->_mysqlOptions.mysqlOptTransaction)   {      // Transaction support enabled      // Make sure a transaction is active      if (!_isTransaction)         throw TransactionError("rollback(): "            "A transaction is not active. Create a transaction before calling commit.");            // Ping the connection to make sure it is still valid.      _parentConnection->_mysqlPing(_index);            string query = "ROLLBACK";      if (mysql_real_query(&_parentConnection->_handles[_index]->__mysql__, query.c_str(), query.length()) != 0)      {         // Something went wrong while trying to execute the sql statement, so throw an exception.         string err = "commit(): Unable to rollback the transaction";         err += ", ";         err += mysql_error(&_parentConnection->_handles[_index]->__mysql__);         throw TransactionError(err);      }         	_isTransaction = false;         }   else   {      // Transaction support not enabled      throw NotImplemented("rollback(): Transaction support is not enabled. Please enable in .ini file with 'mysql_opt_transaction = yes' entry.");   }   }  // MysqlQuery::rollback//------------------------------------------------------------------------------// MysqlQuery::getFieldInfoByColumn//------------------------------------------------------------------------------BaseFieldDescription*MysqlQuery::getFieldInfoByColumn(   int index){   // Make sure the index is in range.   if (index < 0 || index >= _numFieldInformation)      throw IndexOutOfRange("getFieldInfoByColumn(): The field index is out of range for the current result set");   return _fieldInformation[index];}  // MysqlQuery::getFieldInfoByColumn//------------------------------------------------------------------------------// MysqlQuery::getFieldInfoByName//------------------------------------------------------------------------------BaseFieldDescription*MysqlQuery::getFieldInfoByName(   const string& fieldName){   // Try and find the field name   for (int i=0; i<_numFieldInformation; i++)      if (strcasecmp(_fieldInformation[i]->name().c_str(), fieldName.c_str()) == 0)         return _fieldInformation[i];   throw NameNotFound("getFieldInfoByName(): The field name was not found for the current result set.");}  // MysqlQuery::getFieldInfoByName//------------------------------------------------------------------------------// MysqlQuery::getFieldByColumn//------------------------------------------------------------------------------BaseValue*MysqlQuery::getFieldByColumn(   int index){
   // Make sure the index is in range.   if (index < 0 || index >= _numRecordValues)
   {      throw IndexOutOfRange("getFieldByColumn(): The field index is out of range for the current result set");
   }
   return _recordValues[index];}  // MysqlQuery::getFieldByColumn   //------------------------------------------------------------------------------// MysqlQuery::getFieldByName//------------------------------------------------------------------------------BaseValue*MysqlQuery::getFieldByName(   const string& fieldName){   // Try and find the field name   for (int i=0; i<_numRecordValues; i++)      if (strcasecmp(_recordValues[i]->name().c_str(), fieldName.c_str()) == 0)         return _recordValues[i];   throw NameNotFound("getFieldByName(): The field name was not found for the current result set.");   }  // MysqlQuery::getFieldByName

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -