コード例 #1
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult,
		MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount) {
	if (!m_Mysql)
		return false;

	{
		uint32 _s = 0;
		if (sLog->GetSQLDriverQueryLogging())
			_s = getMSTime();

		if (mysql_query(m_Mysql, sql)) {
			uint32 lErrno = mysql_errno(m_Mysql);
			sLog->outSQLDriver("SQL: %s", sql);
			sLog->outSQLDriver("ERROR: [%u] %s", lErrno, mysql_error(m_Mysql));

			if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection)
				return _Query(sql, pResult, pFields, pRowCount, pFieldCount); // We try again

			return false;
		} else if (sLog->GetSQLDriverQueryLogging()) {
			sLog->outSQLDriver("[%u ms] SQL: %s",
					getMSTimeDiff(_s, getMSTime()), sql);
		}

		*pResult = mysql_store_result(m_Mysql);
		*pRowCount = mysql_affected_rows(m_Mysql);
		*pFieldCount = mysql_field_count(m_Mysql);
	}

	if (!*pResult)
		return false;

	if (!*pRowCount) {
		mysql_free_result(*pResult);
		return false;
	}

	*pFields = mysql_fetch_fields(*pResult);

	return true;
}
コード例 #2
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!m_Mysql)
        return false;

    {
        // guarded block for thread-safe mySQL request
        ACE_Guard<ACE_Thread_Mutex> query_connection_guard(m_Mutex);
        #ifdef SQLQUERY_LOG
        uint32 _s = getMSTime();
        #endif
        if (mysql_query(m_Mysql, sql))
        {
            sLog.outSQLDriver("SQL: %s", sql);
            sLog.outSQLDriver("query ERROR: %s", mysql_error(m_Mysql));
            return false;
        }
        else
        {
            #ifdef SQLQUERY_LOG
            sLog.outSQLDriver("[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql);
            #endif
        }

        *pResult = mysql_store_result(m_Mysql);
        *pRowCount = mysql_affected_rows(m_Mysql);
        *pFieldCount = mysql_field_count(m_Mysql);
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
コード例 #3
0
/**
 * Same as am_mysql_simple_query but given an already
 * formatted query and mysql handle
 */
int
_am_mysql_simple_query (MYSQL *mysql, char *fmt_query){
  MYSQL_RES			*result = NULL;
	int rc = -1;
	/* Now for the query itself */
	if (mysql_query(mysql, fmt_query))
	{
		/* query failed */
		rc = -1;
		LOGERROR ("Failed to execute query: Error (%d): %s\n", mysql_errno(mysql), mysql_error(mysql));
		goto _simple_query_free;
	}

	if ((result = mysql_store_result(mysql)) == NULL)
	{
		/*
		* Failed to get result
		* 2 cases:
		*		- no result expected (after an insert statement...
		*		- error getting result
		*/
		if (mysql_field_count (mysql) == 0){
			/* insert like statement, no result expected!, return affected rows; */
			rc = mysql_affected_rows(mysql);
			goto _simple_query_free;
		}else{
			rc = -1;
			LOGERROR ("Failed to store query results: Error (%d): %s\n", mysql_errno(mysql), mysql_error(mysql));
			goto _simple_query_free;
		}
	}

	/* Finally, we just want to know how many rows were returned by query */
	rc = mysql_num_rows(result);

_simple_query_free:
	/* Free resources */
	if (result != NULL)
		mysql_free_result(result);
	return rc;
}
コード例 #4
0
ファイル: core.c プロジェクト: antonioscherrer/harbour-core
static HB_ERRCODE mysqlExecute( SQLDDCONNECTION * pConnection, PHB_ITEM pItem )
{
   MYSQL *     pMySql = ( ( SDDCONN * ) pConnection->pSDDConn )->pMySql;
   MYSQL_RES * pResult;
   HB_ULONG    ulAffectedRows;
   PHB_ITEM    pNewID = NULL;

   if( mysql_real_query( pMySql, hb_itemGetCPtr( pItem ), ( unsigned long ) hb_itemGetCLen( pItem ) ) )
   {
      hb_rddsqlSetError( mysql_errno( pMySql ), mysql_error( pMySql ), hb_itemGetCPtr( pItem ), NULL, 0 );
      return HB_FAILURE;
   }

   pResult = mysql_store_result( pMySql );
   if( pResult )
   {
      ulAffectedRows = ( HB_ULONG ) mysql_num_rows( pResult );
      mysql_free_result( pResult );
      hb_rddsqlSetError( 0, NULL, hb_itemGetCPtr( pItem ), NULL, ulAffectedRows );
   }
   else
   {
      if( mysql_field_count( pMySql ) == 0 )
      {
         ulAffectedRows = ( HB_ULONG ) mysql_affected_rows( pMySql );
         if( mysql_insert_id( pMySql ) != 0 )
         {
            pNewID = hb_itemPutNInt( NULL, mysql_insert_id( pMySql ) );
         }
         hb_rddsqlSetError( 0, NULL, hb_itemGetCPtr( pItem ), pNewID, ulAffectedRows );
         if( pNewID )
            hb_itemRelease( pNewID );
      }
      else /* error */
      {
         hb_rddsqlSetError( mysql_errno( pMySql ), mysql_error( pMySql ), hb_itemGetCPtr( pItem ), NULL, 0 );
         return HB_FAILURE;
      }
   }
   return HB_SUCCESS;
}
コード例 #5
0
ファイル: dbc_common.c プロジェクト: akin520/mysql-benchmark
int dbt2_sql_execute(struct db_context_t *dbc, char * query, struct sql_result_t * sql_result, 
                       char * query_name)
{

  sql_result->result_set= NULL;
  sql_result->num_fields= 0;
  sql_result->num_rows= 0;
  sql_result->query=query;

  if (mysql_query(dbc->mysql, query))
  {
    LOG_ERROR_MESSAGE("%s: %s\nmysql reports: %d %s",query_name, query,
                            mysql_errno(dbc->mysql), mysql_error(dbc->mysql));
    return 0;
  }
  else 
  {
    sql_result->result_set = mysql_store_result(dbc->mysql);

    if (sql_result->result_set)  
    {
      sql_result->num_fields= mysql_num_fields(sql_result->result_set);
      sql_result->num_rows= mysql_num_rows(sql_result->result_set);
    }
    else  
    {
      if (mysql_field_count(dbc->mysql) == 0)
      {
        sql_result->num_rows = mysql_affected_rows(dbc->mysql);
      }
      else 
      {
         LOG_ERROR_MESSAGE("%s: %s\nmysql reports: %d %s",query_name, query,
                            mysql_errno(dbc->mysql), mysql_error(dbc->mysql));
         return 0;
      }
    }
  }

  return 1;
}
コード例 #6
0
ファイル: db_dataset.cpp プロジェクト: F4m3uS/hiphop-php
void DBDataSet::addResult(MYSQL *conn, MYSQL_RES *result) {
  if (result == NULL) return;

  int rowCount = mysql_num_rows(result);
  if (rowCount) {
    int fieldCount = (int)mysql_field_count(conn);
    if (m_colCount == 0) {
      m_colCount = fieldCount;
    } else {
      ASSERT(m_colCount == fieldCount);
      if (m_colCount > fieldCount) {
        m_colCount = fieldCount; // in case we overflow m_row later
      }
    }

    m_rowCount += rowCount;
    m_results.push_back(result);
  } else {
    mysql_free_result(result);
  }
}
コード例 #7
0
MYSQL_RES* MySQLConnection::_MySQLStoreResult(const char* sql, UInt64& outRowCount, size_t& outFieldCount)
{
	MYSQL_RES* outResult = mysql_store_result(_myConn);
	if (outResult)
	{
		outRowCount = mysql_num_rows(outResult);
		outFieldCount = mysql_num_fields(outResult);
	}
	else
	{
		int resultRetVal = mysql_errno(_myConn);
		if (resultRetVal)
			throw SqlException(resultRetVal,mysql_error(_myConn),"MySQLStoreResult",IsConnectionLost(resultRetVal),true,sql);
		else
		{
			outRowCount = mysql_affected_rows(_myConn);
			outFieldCount = mysql_field_count(_myConn);
		}
	}
	return outResult;
}
コード例 #8
0
ファイル: UnitFormDLL.cpp プロジェクト: txe/ieml
//---------------------------------------------------------------------------
int __fastcall TFormDLLProgr::GetSpecIDForStudID(int _idstud)
{
  int myidspec=-1;

  MYSQL_RES *result;
  MYSQL_ROW row;

  AnsiString query="SELECT specid FROM "+opts.DBStudTable+" WHERE deleted=0 AND id="+AnsiString(_idstud);
  mysql_query(mysql,query.c_str());
  if (mysql_field_count(mysql))
  {
    result=mysql_store_result(mysql);
    if (result && mysql_num_rows(result))
    {
      row = mysql_fetch_row(result);
      myidspec=AnsiString(row[0]).ToInt();
    }
    mysql_free_result(result);
  }
  return myidspec;
}
コード例 #9
0
ファイル: MySQLDatabase.cpp プロジェクト: AscEmu/AscEmu
QueryResult* MySQLDatabase::_StoreQueryResult(DatabaseConnection* con)
{
    MySQLQueryResult* res;
    MySQLDatabaseConnection* db = static_cast<MySQLDatabaseConnection*>(con);
    MYSQL_RES* pRes = mysql_store_result(db->MySql);
    uint32 uRows = (uint32)mysql_affected_rows(db->MySql);
    uint32 uFields = (uint32)mysql_field_count(db->MySql);

    if(uRows == 0 || uFields == 0 || pRes == 0)
    {
        if(pRes != NULL)
            mysql_free_result(pRes);

        return NULL;
    }

    res = new MySQLQueryResult(pRes, uFields, uRows);
    res->NextRow();

    return res;
}
コード例 #10
0
ファイル: DBConn.cpp プロジェクト: kimeyongchan/MobileStar
bool DBConn::ProcessResultQuery(const char* query, MYSQL_RES** resultSet)
{
    //DebugLog("%s", query);
    if (0 != mysql_query(_conn, query))
    {
        MysqlErrorLog("could not excute query");
        return false;
    }
    
    *resultSet = mysql_store_result(_conn);
    if (NULL == *resultSet)
    {
        if (mysql_field_count(_conn) != 0)
        {
            MysqlErrorLog("could not retrieve result set");
            return false;
        }
    }
    
    return true;
}
コード例 #11
0
ファイル: 59mysql.c プロジェクト: qiubinren/exercise
int main()
{
	MYSQL mysql;
	MYSQL_RES *res;
	MYSQL_ROW row;
	char* query="select * from test;";
	int t,r;
	mysql_init(&mysql);
	if(!mysql_real_connect(&mysql,"localhost","root","","test2",0,NULL,0))
	{
		printf("Error connecting to database:%s\n",mysql_error(&mysql));
	}
	else
		printf("Connected...");
	t=mysql_query(&mysql,query);
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(&mysql));
	}
	else
	{
		printf("Query made...\n");
		res = mysql_use_result(&mysql);
		if(res)
		{
			for(r=0;r<mysql_field_count(&mysql);r++)
			{
				row=mysql_fetch_row(res);
				if(row<0)
					break;
				for(t=0;t<mysql_num_fields(res);t++)
					printf("%s ",row[t]);
				printf("\n");
			}
		}
		mysql_free_result(res);
	}
	mysql_close(&mysql);
	return 0;
}
コード例 #12
0
ファイル: DatabaseMysql.cpp プロジェクト: Maduse/server
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    uint32 _s = WorldTimer::getMSTime();

    if (mysql_query(mMysql, sql))
    {
        uint32 lErrno = mysql_errno(mMysql);

        sLog.outErrorDb( "SQL: %s", sql);
        sLog.outErrorDb("[%u] %s", lErrno, mysql_error(mMysql));

        if (HandleMySQLError(lErrno)) // If error is handled, just try again
            return _Query(sql, pResult, pFields, pRowCount, pFieldCount);

        return false;
    }
    else
    {
        DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", WorldTimer::getMSTimeDiff(_s,WorldTimer::getMSTime()), sql );
    }

    *pResult = mysql_store_result(mMysql);
    *pRowCount = mysql_affected_rows(mMysql);
    *pFieldCount = mysql_field_count(mMysql);

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
コード例 #13
0
void CDatabaseConnection::NonQuery(const std::string& queryString)
{
	// We don't want concurrent queries
	std::lock_guard<std::mutex> lock{_dbMutex};

	while(mysql_query(_pMySQL, queryString.c_str()) != 0)
	{
		Log(CLog::Error, StrFormat("Error executing query {0}. ({1})", queryString, Error()));
		connect();
	}

	s32 status;
	do
	{
		/* did current statement return data? */
		MYSQL_RES* pRes = mysql_store_result(_pMySQL);
		if(pRes != NULL)
		{
			mysql_free_result(pRes);
		}
		else          /* no result set or error */
		{
			if(mysql_field_count(_pMySQL) == 0)
			{
			}
			else  /* some error occurred */
			{
				throw CDatabaseException(SRC_POS, StrFormat("Error getting result. ({0})", Error()));
			}
		}
		/* more results? -1 = no, >0 = error, 0 = yes (keep looping) */

		status = mysql_next_result(_pMySQL);
		if(status > 0)
		{
			throw CDatabaseException(SRC_POS, StrFormat("Error executing query {0}. ({1})", queryString, Error()));
		}
	}
	while(status == 0);
}
コード例 #14
0
void
process_statement (MYSQL *conn, char *stmt_str)
{
MYSQL_RES *res_set;

  if (mysql_query (conn, stmt_str) != 0)  /* the statement failed */
  {
    print_error (conn, "Could not execute statement");
    return;
  }

  /* the statement succeeded; determine whether it returned data */
  res_set = mysql_store_result (conn);
  if (res_set)      /* a result set was returned */
  {
    /* process rows and free the result set */
    process_result_set (conn, res_set);
    mysql_free_result (res_set);
  }
  else              /* no result set was returned */
  {
    /*
     * does the lack of a result set mean that the statement didn't
     * return one, or that it should have but an error occurred?
     */
    if (mysql_field_count (conn) == 0)
    {
      /*
       * statement generated no result set (it was not a SELECT,
       * SHOW, DESCRIBE, etc.); just report rows-affected value.
       */
      printf ("Number of rows affected: %lu\n",
              (unsigned long) mysql_affected_rows (conn));
    }
    else  /* an error occurred */
    {
      print_error (conn, "Could not retrieve result set");
    }
  }
}
コード例 #15
0
ファイル: cyrusdb_sql.c プロジェクト: larsks/cyrus-imapd-lks
static int _mysql_exec(void *conn, const char *cmd, exec_cb *cb, void *rock)
{
    MYSQL_RES *result;
    MYSQL_ROW row;
    int len, r = 0;

    syslog(LOG_DEBUG, "executing SQL cmd: %s", cmd);

    len = strlen(cmd);
    /* mysql_real_query() doesn't want a terminating ';' */
    if (cmd[len-1] == ';') len--;

    /* run the query */
    if ((mysql_real_query(conn, cmd, len) < 0) ||
	*mysql_error(conn)) {
	syslog(LOG_ERR, "DBERROR: SQL query failed: %s", mysql_error(conn));
	return CYRUSDB_INTERNAL;
    }

    /* see if we should expect some results */
    if (!mysql_field_count(conn)) {
	/* no results (BEGIN, COMMIT, ROLLBACK, CREATE, INSERT, UPDATE, DELETE) */
	syslog(LOG_DEBUG, "no results from SQL cmd");
	return 0;
    }

    /* get the results */
    result = mysql_store_result(conn);
    
    /* process the results */
    while (!r && (row = mysql_fetch_row(result))) {
	unsigned long *length = mysql_fetch_lengths(result);
	r = cb(rock, row[0], length[0], row[1], length[1]);
    }

    /* free result */
    mysql_free_result(result);
    
    return r;
}
コード例 #16
0
/*************************************************************************//**
Execute any query contained in the input string.

@retval false if no error. True if error

If the query is a select query which returns a value, the results have to be
retirieved by calling getNextRow()
														 
*****************************************************************************/
bool MySqlConnection::query(const std::string queryStr)
{
	// Execute the query
	int res = mysql_real_query(&connection, queryStr.c_str(), queryStr.size());
	if (res)
	{
		errorPrint();
		return true;
	}
	// Check if there are results as expected

	resetQueryResultInfo();
	result = mysql_store_result(& connection);
	if (result)  // there are rows
	{
		// Retrieve information about the results
		hasRows = true;
		num_fields = mysql_num_fields(result);
		fields = mysql_fetch_fields(result);
		// There is an issue here because mysql_store_result was called but mysql_free_results was not
		// However as we are using only insert queries in this program this should be acceptable

	}
	else  // mysql_store_result() returned nothing; should it have?
	{
		if (mysql_field_count(& connection) == 0)
		{
			// query does not return data
			// (it was not a SELECT)
			num_rows = mysql_affected_rows(&connection);
			//assert(num_rows == 1);
		}
		else // mysql_store_result() should have returned data
		{
			errorPrint();
		}
	}

	return false;
}
コード例 #17
0
ファイル: UnitFormDLL.cpp プロジェクト: txe/ieml
//---------------------------------------------------------------------------
void __fastcall TFormDLL::BtnAllFactsClick(TObject *Sender)
{
  ListBoxPrevOplata->Clear();
  listIDFacts->Clear();

  AnsiString IDStudStr=AnsiString(idstud);
  AnsiString StrForListBox;

  EditSumMoney->Text="нет категории";
  EditDolg->Text="нет категории";
  ListBoxPrevOplataClick(ListBoxPrevOplata);

  ListBoxPrevOplata->Items->Add(" Дата оплаты           Сумма оплаты           Группа");
  listIDFacts->Add("");
  ListBoxPrevOplata->Items->Add("");
  listIDFacts->Add("");

  MYSQL_RES *result;
  MYSQL_ROW row;
         // id для удаления фактов
  AnsiString query="SELECT f.id,f.datepay,f.moneypay,op.idgroup FROM "+opts.DBPayFacts+" as f, "+opts.DBPayOpts+" as op WHERE f.deleted=0 AND op.deleted=0 AND f.idstud="+IDStudStr+" AND f.idopts=op.id ORDER BY f.datepay";
  mysql_query(mysql,query.c_str());
  if (mysql_field_count(mysql))
  {
    result=mysql_store_result(mysql);
    if (result && mysql_num_rows(result))
    {
      while (row = mysql_fetch_row(result))
      {
        StrForListBox=" "+ReturnParsedDateInMask(AnsiString(row[1]))+"                  "+AnsiString(row[2])+"                           "+WCGetTitleForKeyNum(GROUPS,AnsiString(row[3]).ToInt());

        listIDFacts->Add("");
        ListBoxPrevOplata->Items->Add(StrForListBox);
      }
    }
    mysql_free_result(result);
  }

  ListBoxPrevOplataClick(ListBoxPrevOplata);
}
コード例 #18
0
ファイル: mysql.c プロジェクト: Hmaal/slash
static SLVAL
sl_mysql_raw_query(sl_vm_t* vm, SLVAL self, SLVAL query)
{
    mysql_t* mysql = get_mysql(vm, self);
    sl_string_t* str = sl_get_string(vm, query);

    if(mysql_real_query(&mysql->mysql, (char*)str->buff, str->buff_len)) {
        sl_mysql_check_error(vm, &mysql->mysql);
    }

    MYSQL_RES* result;
    if((result = mysql_store_result(&mysql->mysql))) {
        /* do shit */
        int ncolumns = mysql_num_fields(result);
        int nrows = mysql_num_rows(result);
        SLVAL* rows = sl_alloc(vm->arena, sizeof(SLVAL) * nrows);
        MYSQL_FIELD* fields = mysql_fetch_fields(result);
        for(int i = 0; i < nrows; i++) {
            SLVAL* cells = sl_alloc(vm->arena, sizeof(SLVAL) * ncolumns * 2);
            MYSQL_ROW row = mysql_fetch_row(result);
            size_t* lengths = mysql_fetch_lengths(result);
            for(int j = 0; j < ncolumns; j++) {
                cells[j * 2] = sl_make_cstring(vm, fields[j].name);
                if(row[j]) {
                    cells[j * 2 + 1] = sl_make_string(vm, (uint8_t*)row[j], lengths[j]);
                } else {
                    cells[j * 2 + 1] = vm->lib.nil;
                }
            }
            rows[i] = sl_make_dict(vm, ncolumns, cells);
        }
        mysql_free_result(result);
        return sl_make_array(vm, nrows, rows);
    } else {
        if(mysql_field_count(&mysql->mysql) != 0) {
            sl_mysql_check_error(vm, &mysql->mysql);
        }
        return sl_make_int(vm, mysql_affected_rows(&mysql->mysql));
    }
}
コード例 #19
0
ファイル: MySQLQuery.cpp プロジェクト: gityf/db
int MySQLQuery::next(std::vector<char*>& row_data) {
    if (!conn_) {
        LOG_WARN("event=[mysqlquery] type=[execute] status=[invalid]");
        return Status::NOHANLDER;
    }
    row_data.clear();

    MYSQL_ROW row = nullptr;
    MYSQL* mysql = conn_->handler();
    if (!mysql) {
        LOG_WARN("event=[mysqlquery] type=[execute] status=[invalid]");
        return Status::NOHANLDER;
    }
    if (!result_) {
        LOG_WARN("event=[mysqlquery] type=[execute] status=[invalid]");
        return Status::NORESULT;
    }
    row = mysql_fetch_row(result_);
    if (!row) {
        //null row and none 0 errno, indicationg an error
        if (mysql_errno(mysql)) {
            LOG_WARN("event=[mysqlquery] type=[execute] status=[failed] message=[%s]",
                mysql_error(mysql));
            return Status::FAILED;
        } else {
            if (result_) {
                mysql_free_result(result_);
                result_ = nullptr;
            }
            return Status::OK;
        }
    }
    int fields_num = mysql_field_count(mysql);
    row_data.reserve(fields_num);

    for (int i = 0; i < fields_num; ++i) {
        row_data.push_back(row[i]);
    }
    return Status::OK;
}
コード例 #20
0
bool MySQLConnection::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!m_Mysql)
        return false;

    {
       boost::timer _s;

        if (mysql_query(m_Mysql, sql))
        {
            uint32 lErrno = mysql_errno(m_Mysql);
            _LOG_INFO(LOG_FILTER_SQL, "SQL: %s", sql);
            _LOG_ERROR(LOG_FILTER_SQL, "[%u] %s", lErrno, mysql_error(m_Mysql));

            if (_HandleMySQLErrno(lErrno))      // If it returns true, an error was handled successfully (i.e. reconnection)
                return _Query(sql, pResult, pFields, pRowCount, pFieldCount);    // We try again

            return false;
        }
        else
            _LOG_DEBUG(LOG_FILTER_SQL, "[%u ms] SQL: %s",(uint32)_s.elapsed(), sql);

        *pResult = mysql_store_result(m_Mysql);
        *pRowCount = mysql_affected_rows(m_Mysql);
        *pFieldCount = mysql_field_count(m_Mysql);
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);

    return true;
}
コード例 #21
0
int oph_odb_extract_datacube_ids(ophidiadb * oDB, char *query, cube ** datacube, int *counter)
{
	if (!oDB || !query || !datacube || !counter)
		return OPH_ODB_NULL_PARAM;

	if (oph_odb_check_connection_to_ophidiadb(oDB))
		return OPH_ODB_MYSQL_ERROR;

	if (mysql_query(oDB->conn, query))
		return OPH_ODB_MYSQL_ERROR;

	MYSQL_RES *res;
	MYSQL_ROW row;
	res = mysql_store_result(oDB->conn);

	if (mysql_field_count(oDB->conn) != 2) {
		mysql_free_result(res);
		return OPH_ODB_TOO_MANY_ROWS;
	}

	*counter = mysql_num_rows(res);
	if (!(*counter)) {
		mysql_free_result(res);
		return OPH_ODB_SUCCESS;
	}

	if (!(*datacube = (cube *) malloc(*counter * sizeof(cube)))) {
		mysql_free_result(res);
		return OPH_ODB_MEMORY_ERROR;
	}

	int i = 0;
	while ((row = mysql_fetch_row(res)) != NULL) {
		(*datacube)[i].id_datacube = (row[0] ? (int) strtol(row[0], NULL, 10) : 0);
		(*datacube)[i].id_container = (row[1] ? (int) strtol(row[1], NULL, 10) : 0);
		i++;
	}
	mysql_free_result(res);
	return OPH_ODB_SUCCESS;
}
コード例 #22
0
ファイル: DatabaseMysql.cpp プロジェクト: Archives/try
bool DatabaseMysql::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
    if (!mMysql)
        return 0;

    {
        // guarded block for thread-safe mySQL request
        ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);

        uint32 _s = getMSTime();

        if (mysql_query(mMysql, sql))
        {
            sLog.outErrorDb( "SQL: %s", sql );
            sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
            return false;
        }
        else
        {
            DEBUG_FILTER_LOG(LOG_FILTER_SQL_TEXT, "[%u ms] SQL: %s", getMSTimeDiff(_s,getMSTime()), sql );
        }

        *pResult = mysql_store_result(mMysql);
        *pRowCount = mysql_affected_rows(mMysql);
        *pFieldCount = mysql_field_count(mMysql);
        // end guarded block
    }

    if (!*pResult )
        return false;

    if (!*pRowCount)
    {
        mysql_free_result(*pResult);
        return false;
    }

    *pFields = mysql_fetch_fields(*pResult);
    return true;
}
コード例 #23
0
ファイル: dbbase.cpp プロジェクト: schidler/code
/**
 * @brief select_query 
 * 查找操作
 * @Param: sql   查找sql 命令
 * @Param: retstr  返回列字段,以逗号隔开
 *
 * Returns: 
 */
static int select_query(const string & sql, string &retstr)
{
	check_connect();

	int nRet = mysql_query(&m_mysqlfd, sql.c_str());
	if (nRet != 0)
	{
		LOG_ERROR("mysql_query failed select error:%s\n ", mysql_error(&m_mysqlfd));
		return -1;
	}

	MYSQL_RES   *pres = mysql_use_result(&m_mysqlfd);//返回执行结果,适用于数据量较大时
	if (pres == NULL)
	{
		LOG_ERROR("mysql_use_result failed\n ");
		return -1;
	}

	Uint32 fieldcoun = mysql_field_count(&m_mysqlfd);//返回查询结果中的列数(column数)
	Uint32 index = 0;
	MYSQL_ROW  mysqlrow;
	while ((mysqlrow = mysql_fetch_row(pres)) != NULL)
	{//后继的调用正常返回的内容
		index = 0;
		while (index < fieldcoun)
		{
			if (mysqlrow[index])
			{
				retstr.append(mysqlrow[index]);
				retstr.append(",");
			}
			index++;
		}
		LOG_DEBUG("select success fieldcoun=%d len=%ld ret=%s\n", fieldcoun, retstr.length(), retstr.c_str());
	}
	mysql_free_result(pres);

	return retstr.empty()?1:0;
}
コード例 #24
0
ファイル: UnitFormDLL.cpp プロジェクト: txe/ieml
//---------------------------------------------------------------------------
void __fastcall TFormDLLProgr::UpdateVKR(void)
{
  MYSQL_RES *result;
  MYSQL_ROW row;

  AnsiString VKRTitle="";
  AnsiString myquery;
  myquery="SELECT vkr_title FROM "+opts.DBStudTable+" WHERE id="+ToStr(AnsiString(GetIDCurStud()));
  mysql_query(mysql,myquery.c_str());
  if (mysql_field_count(mysql))
  {
    result=mysql_store_result(mysql);
    if (result && mysql_num_rows(result))
    {
      row = mysql_fetch_row(result);
      VKRTitle = AnsiString(row[0]);
    }
    mysql_free_result(result);
  }

  EditVKRTitle->Text = VKRTitle;
}
コード例 #25
0
ファイル: sqlhandler.c プロジェクト: maomaotp/base_code
int stores_Sql_Exec(MYSQL* mysql, char* sql, void (*call_back)(char** result, int column, void* param), void* param)
{
	if(mysql_query(mysql,sql)) {
		printf("error making query:%s\n",mysql_error(mysql));
		return -1;
	}
	MYSQL_RES* res=mysql_use_result(mysql);//获取查询结果
	if(!res) {
		printf("err use_result:%s\n",mysql_error(mysql));
		return -2;
	}
	MYSQL_ROW row;
	int column_count=mysql_field_count(mysql);
	while(1)
	{
		row=mysql_fetch_row(res);
		if(!row)break;
		call_back((char**)row,column_count,param);
	}
	mysql_free_result(res);
	return 1;
}
コード例 #26
0
ファイル: mysql.c プロジェクト: diroussel/lua-web-tools
/*
 * Executes an SQL statement directly. This is required for statements
 * which cannot be prepared.
 */
static int execute_direct (lua_State *L) {
    mysql_rec *m;
    const char *sql;
    MYSQL_RES *res;

    m = (mysql_rec *) luaL_checkudata(L, 1, IS_MYSQL_METATABLE);
    if (!m->mysql) {
        lua_pushliteral(L, "connection is closed");
        lua_error(L);
    }
    sql = luaL_checkstring(L, 2);

    /* close open statement */
    if (m->res) {
        mysql_free_result(m->res);
        m->res = NULL;
    }
    if (m->stmt) {
        mysql_stmt_close(m->stmt);
        m->stmt = NULL;
    }

    /* execute */
    if (mysql_real_query(m->mysql, sql, lua_rawlen(L, 2)) != 0) {
        error(L, m);
    }
    if (mysql_field_count(m->mysql) > 0) {
        /* discard result set, if any */
        if  ((res = mysql_store_result(m->mysql)) == NULL) {
            error(L, m);
        }
        mysql_free_result(res);
        return 0;
    } else {
        /* push number of affected rows */
        lua_pushinteger(L, (lua_Integer) mysql_affected_rows(m->mysql));
        return 1;
    }
}
コード例 #27
0
static int aMYSQL_query(struct cw_channel *chan, char *data) {
	
	MYSQL       *mysql;
	MYSQL_RES   *mysqlres;

	char *resultid_var;
	int connid;
	char *querystring;

	strsep(&data," "); // eat the first token, we already know it :P 

	resultid_var = strsep(&data," ");
	connid       = safe_scan_int(&data," ",-1);
	querystring  = strsep(&data,"\n");

	if (resultid_var && (connid>=0) && querystring) {
		if ((mysql=find_identifier(connid,CW_MYSQL_ID_CONNID))!=NULL) {
			mysql_query(mysql,querystring);
			if ((mysqlres=mysql_use_result(mysql))!=NULL) {
				add_identifier_and_set_callweaver_int(chan,resultid_var,CW_MYSQL_ID_RESID,mysqlres);
				return 0;
			}
			else if( mysql_field_count(mysql)==0 ) {
				return 0;  // See http://dev.mysql.com/doc/mysql/en/mysql_field_count.html
			}
			else {
				cw_log(LOG_WARNING,"aMYSQL_query: mysql_store_result() failed on query %s\n",querystring);
			}
		}
		else {
			cw_log(LOG_WARNING,"aMYSQL_query: Invalid connection identifier %d passed in aMYSQL_query\n",connid);
		}
	}
	else {
		cw_log(LOG_WARNING,"aMYSQL_query: missing some arguments\n");
	}
	
	return -1;
}
コード例 #28
0
ファイル: client.c プロジェクト: 0xCCD/mysql2
static VALUE rb_mysql_client_async_result(VALUE self) {
  MYSQL_RES * result;
  VALUE resultObj;
#ifdef HAVE_RUBY_ENCODING_H
  mysql2_result_wrapper * result_wrapper;
#endif
  GET_CLIENT(self);

  // if we're not waiting on a result, do nothing
  if (!wrapper->active)
    return Qnil;

  REQUIRE_OPEN_DB(wrapper);
  if (rb_thread_blocking_region(nogvl_read_query_result, wrapper->client, RUBY_UBF_IO, 0) == Qfalse) {
    // an error occurred, mark this connection inactive
    MARK_CONN_INACTIVE(self);
    return rb_raise_mysql2_error(wrapper);
  }

  result = (MYSQL_RES *)rb_thread_blocking_region(nogvl_store_result, wrapper, RUBY_UBF_IO, 0);

  if (result == NULL) {
    if (mysql_field_count(wrapper->client) != 0) {
      rb_raise_mysql2_error(wrapper);
    }
    return Qnil;
  }

  resultObj = rb_mysql_result_to_obj(result);
  // pass-through query options for result construction later
  rb_iv_set(resultObj, "@query_options", rb_funcall(rb_iv_get(self, "@query_options"), rb_intern("dup"), 0));

#ifdef HAVE_RUBY_ENCODING_H
  GetMysql2Result(resultObj, result_wrapper);
  result_wrapper->encoding = wrapper->encoding;
#endif
  return resultObj;
}
コード例 #29
0
ファイル: MySQLp.cpp プロジェクト: huangyt/MyProjects
	bool MySQLp::Query(const string &query)
		//执行SQL语句 成功返回真 并将结果存放在 resluts_中 如果没有结果 resluts_.size() == 0
	{
		MYSQL_RES *results;
		MYSQL_ROW record;
		int num_fields;	 

		results_.clear();

		if(mysql_query(&mysql_, query.c_str()))
		{
			u_int err = mysql_errno(&mysql_);
			
			RELEASE_LOG("数据库操作失败,错误代码 " << err << ": " << mysql_error(&mysql_)); 
			//INDEX_EVENT("数据库操作失败,错误代码 " << err); 
			
			return false;
		}

		if(mysql_field_count(&mysql_))
		{
			results = mysql_store_result(&mysql_);
			num_fields = mysql_num_fields(results);

			while((record = mysql_fetch_row(results)))
			{
				vector<string> rslt_line;
				for(int i = 0; i < num_fields; i++ )
				{
					rslt_line.push_back(string(record[i]));
				}
				results_.push_back(rslt_line);
				rslt_line.clear();
			}
			mysql_free_result(results);
		}
		return true;
	}
コード例 #30
0
ファイル: UnitInsertVoc.cpp プロジェクト: txe/ieml
//---------------------------------------------------------------------------
void __fastcall TFormInsertVoc::InitTable(AnsiString WHEREStr,AnsiString KeyOrder)
{
       MYSQL_RES *result;
       MYSQL_ROW row;

       AnsiString myquery="SELECT id,vkey,num,title FROM "+TabVocName+" "+WHEREStr+" ORDER BY "+KeyOrder;
       mysql_query(mysql,myquery.c_str());
       Memo1->Lines->Add(mysql_error(mysql));
       int numCurRow;
       if (mysql_field_count(mysql))
       {
         Memo1->Lines->Add(mysql_error(mysql));
         result=mysql_store_result(mysql);
         Memo1->Lines->Add(mysql_error(mysql));
         if (result && mysql_num_rows(result))
         {
           Memo1->Lines->Add(mysql_error(mysql));

           numCurRow=0;
           listIDsVoc->Clear();
           listIDsVoc->Add("NULL");
           while (row = mysql_fetch_row(result))
           {
                Memo1->Lines->Add(mysql_error(mysql));

                numCurRow++;
                StrGridVoc->RowCount=numCurRow+1;

                listIDsVoc->Add(AnsiString(row[0]));
                StrGridVoc->Cells[0][numCurRow]=row[1];
                StrGridVoc->Cells[1][numCurRow]=row[2];
                StrGridVoc->Cells[2][numCurRow]=row[3];
           }
         }
         mysql_free_result(result);
         Memo1->Lines->Add(mysql_error(mysql));
       }
}