Exemple #1
0
string DBConn::Query_all_mr_mysql(string sql, string name) {

    Json::Value root;
    Json::Value arrayObj;
    Json::Value item;
    int t = mysql_real_query(&mysql, sql.c_str(),
                             (unsigned int) strlen(sql.c_str()));
    if (t == -1) {
        cout << "query failed:%s\n" << mysql_errno(&mysql)
             << mysql_error(&mysql) << endl;
    } else {
        res = mysql_store_result(&mysql); //返回查询的全部结果集
        //获取表的列数
        //int numb=mysql_num_fields(res);
        //printf("name: %s   count: %d\n", namebuf[i], rows);

        //获取并输出表头
        field = mysql_fetch_fields(res);
        //int length=mysql_fetch_lengths(res);
        int length = mysql_num_rows(res);
        int num = 0;
        int i = 1;
        while (row = mysql_fetch_row(res)) {	//mysql_fetch_row取结果集的下一行
            for (t = 0; t < mysql_num_fields(res); t++) {	//结果集的列的数量
                if (field[t].name != "meetroom_remark") {
                    item[field[t].name] = Json::Value(row[t]);
                }
            }
            arrayObj.append(item);
            item.clear();
            num++;
        }
        root["Num"] = Json::Value(num);
        root[name] = arrayObj;
        return root.toStyledString();
    }

}
Exemple #2
0
static VALUE rb_mysql_result_fetch_field(VALUE self, unsigned int idx, short int symbolize_keys) {
  mysql2_result_wrapper * wrapper;

  GetMysql2Result(self, wrapper);

  if (wrapper->fields == Qnil) {
    wrapper->numberOfFields = mysql_num_fields(wrapper->result);
    wrapper->fields = rb_ary_new2(wrapper->numberOfFields);
  }

  VALUE rb_field = rb_ary_entry(wrapper->fields, idx);
  if (rb_field == Qnil) {
    MYSQL_FIELD *field = NULL;
#ifdef HAVE_RUBY_ENCODING_H
    rb_encoding *default_internal_enc = rb_default_internal_encoding();
    rb_encoding *conn_enc = rb_to_encoding(rb_iv_get(self, "@encoding"));
#endif

    field = mysql_fetch_field_direct(wrapper->result, idx);
    if (symbolize_keys) {
      char buf[field->name_length+1];
      memcpy(buf, field->name, field->name_length);
      buf[field->name_length] = 0;
      rb_field = ID2SYM(rb_intern(buf));
    } else {
      rb_field = rb_str_new(field->name, field->name_length);
#ifdef HAVE_RUBY_ENCODING_H
      rb_enc_associate(rb_field, conn_enc);
      if (default_internal_enc) {
        rb_field = rb_str_export_to_enc(rb_field, default_internal_enc);
      }
#endif
    }
    rb_ary_store(wrapper->fields, idx, rb_field);
  }

  return rb_field;
}
Exemple #3
0
BOOL MySQL_CheckCharacterSet(MYSQL* pHandle)
{
    BOOL        bResult         = false;
    int         nRetCode        = 0;
    char        szSQL[]         = "show variables like \'character_set_database\'";
    MYSQL_RES*  pResultSet      = NULL;
    MYSQL_ROW   Row             = NULL;
    unsigned    uFieldCount     = 0;

    assert(pHandle);
    
    // get database character set
    nRetCode = MySQL_Query(pHandle, szSQL);
    KGLOG_PROCESS_ERROR(nRetCode);

    pResultSet = mysql_store_result(pHandle);
    KGLOG_PROCESS_ERROR(pResultSet);

    uFieldCount = mysql_num_fields(pResultSet);    
    KGLOG_PROCESS_ERROR(uFieldCount == 2);

    Row = mysql_fetch_row(pResultSet);
    KGLOG_PROCESS_ERROR(Row);

    KGLOG_PROCESS_ERROR(Row[1]);

    nRetCode = mysql_set_character_set(pHandle, Row[1]);    
    KGLOG_PROCESS_ERROR(nRetCode == 0);

    bResult = true;
Exit0:
    if (pResultSet)
    {
        mysql_free_result(pResultSet);
        pResultSet = NULL;
    }
    return bResult;
}
Exemple #4
0
	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;
	}
int get_project_description(const char* p_id, std::stringstream& desc)
{
    char query[MAX_QUERY];
    MYSQL_RES* res;
    MYSQL_ROW row;
    sprintf(query,"SELECT description, sopath, picpath, name  FROM projects WHERE p_id = %s",p_id);
    if( mysql_query(conn,query) !=0)
        return -1;

    res = mysql_store_result(conn);
    if(res == NULL)
    {
      printf("Error: can't get the result description\n");
      return -1;
    }

    // Получаем первую строку из результирующей таблицы


    printf("[DB]: fetching..... %d rows\n",mysql_num_rows(res));

    row = mysql_fetch_row(res);

    if( row != NULL && mysql_num_rows (res) > 0 )
    {
        int num_fields = mysql_num_fields(res);
        if (num_fields < TBL_PROJECTS_FIELDS)
            return -1;
        desc<<"Description="<<row[0]<<"\nSoPath="<<row[1]<<"\nPicPath="<<row[2]<<"\nName="<<row[3]<<"\n\n";
    }else
    {
        printf("[DB] error fetching:(\n");
        return -1;
    }
    std::cout<<desc.str();
    return 0;

}
Exemple #6
0
u4 AMySQLServer::_processQueryAllRows(MYSQL_RES *pmyresult, AResultSet& target)
{
  u4 rowCount = 0;
  if (pmyresult)
  {
    MYSQL_ROW myrow;
    rowCount = (int)mysql_num_rows(pmyresult);

    if (rowCount == 0)
      return 0;

    //a_Get field info
    MYSQL_FIELD *fields = mysql_fetch_fields(pmyresult);
    u4 num_fields = mysql_num_fields(pmyresult);

    //a_Set up field data
    for (u4 u=0; u<num_fields; ++u)
      target.useFieldNames().push_back(fields[u].name);

    //a_Populate results
    AString str;
    myrow = mysql_fetch_row(pmyresult);
    while (myrow)
    {
      VECTOR_AString& row = target.insertRow();
      row.reserve(num_fields);
      for(u4 field=0; field < num_fields; ++field)
      {
        row.push_back(myrow[field]);
      }
      
      myrow = mysql_fetch_row(pmyresult);
    }
  }

  mysql_free_result(pmyresult);
  return rowCount;
}
Exemple #7
0
static value alloc_result( MYSQL_RES *r ) {
	result *res = (result*)alloc(sizeof(result));
	value o = alloc_abstract(k_result,res);
	int num_fields = mysql_num_fields(r);
	int i,j;
	MYSQL_FIELD *fields = mysql_fetch_fields(r);
	res->r = r;
	res->conv_date = NULL;
	res->current = NULL;
	res->nfields = num_fields;
	res->fields_ids = (field*)alloc_private(sizeof(field)*num_fields);
	res->fields_convs = (CONV*)alloc_private(sizeof(CONV)*num_fields);
	for(i=0;i<num_fields;i++) {
		field id;
		if( strchr(fields[i].name,'(') )
			id = val_id("???"); // looks like an inner request : prevent hashing + cashing it
		else {
			id = val_id(fields[i].name);
			for(j=0;j<i;j++)
				if( res->fields_ids[j] == id ) {
					buffer b = alloc_buffer("Error, same field ids for : ");
					buffer_append(b,fields[i].name);
					buffer_append(b,":");
					val_buffer(b,alloc_int(i));
					buffer_append(b," and ");
					buffer_append(b,fields[j].name);
					buffer_append(b,":");
					val_buffer(b,alloc_int(j));
					buffer_append(b,".");
					bfailure(b);
				}
		}
		res->fields_ids[i] = id;
		res->fields_convs[i] = convert_type(fields[i].type,fields[i].length);
	}
	val_gc(o,free_result);
	return o;
}
/**
 * Prove data from user login, use username for database query.
 *
 * @param string username Username to prove against database.
 * @param string password The password stored in database will be in this.
 * @param integer maxLength Maximum length of username and password.
 */
int proveUserData(char *username, char *password, int maxLength) {
	MYSQL *connection;
	MYSQL_RES *result;
	MYSQL_ROW row;
	unsigned long *lengths;
	
	connection = mysql_init(NULL);
	if (!mysql_real_connect(connection, MYSQL_HOSTNAME, MYSQL_USERNAME,
			MYSQL_PASSWORD, MYSQL_DATABASE, 0, NULL, 0)) {
		return 1;
	}

	char *usernameEscaped = malloc(maxLength* sizeof(char));

	mysql_real_escape_string(connection, usernameEscaped, username, min(strlen(username), maxLength));
	char *selectQuery = malloc((strlen(usernameEscaped)+strlen(MYSQL_QUERY))*sizeof(char));
	sprintf(selectQuery, MYSQL_QUERY, usernameEscaped);

	if (mysql_query(connection, selectQuery) != 0) {
		return 2;
	}

	result = mysql_store_result(connection);
	if (mysql_num_fields(result) < 1) {
		return 3;
	}
	if (mysql_num_rows(result) < 1) {
		return 4;
	}
	row = mysql_fetch_row(result);
	lengths = mysql_fetch_lengths(result);

	strncpy(password, row[0], min(maxLength, lengths[0]));
	
	mysql_free_result(result);
	mysql_close(connection);
	return 0;
}
int DBSpool::ExecuteSQL(const string& strSQL, RESDataList* res, int &iRelt, unsigned long long* iInsertId)
{
    MYSQL_RES* SQLRes = NULL;
    short shIdt = 0;
    int iRet = ExecuteSQL(strSQL, &SQLRes, shIdt, iRelt, iInsertId);
    if (iRet == SQL_TYPE_SELECT){
        //MYSQL_FIELD* fields;
        MYSQL_ROW row;
        int irows, ifields;
        string strValue;
        irows = mysql_num_rows(SQLRes);
        if(irows == 0) {
            ReleaseConnection(shIdt);
            return iRet;
        }
        ifields = mysql_num_fields(SQLRes);
        if(ifields == 0){
            ReleaseConnection(shIdt);
            return iRet;
        }
        //fields = mysql_fetch_fields(SQLRes);
        for(int i=0; i<irows; i++){
            if((row = mysql_fetch_row(SQLRes)) == NULL){
                break;
            }
            for(int j=0; j<ifields; j++) {
                if (row[j]){
                    strValue = row[j];
                }else{
                    strValue = "";
                }
                res->push_back(strValue);
            }
        }
        ReleaseConnection(shIdt);
    }
    return iRet;
}
Exemple #10
0
MyBoundResults::MyBoundResults(MYSQL_STMT *stmt, MYSQL_RES *res)
: m_stmt(stmt), m_pRes(res), m_Initialized(false), m_RowCount(0), m_CurRow(0)
{
	/**
	 * Important things to note here: 
	 * 1) We're guaranteed at least one field.
	 * 2) The field information should never change, and thus we
	 *    never rebuild it.  If someone ALTERs the table during
	 *    a prepared query's lifetime, it's their own death.
	 */

	m_ColCount = (unsigned int)mysql_num_fields(m_pRes);

	/* Allocate buffers */
	m_bind = (MYSQL_BIND *)malloc(sizeof(MYSQL_BIND) * m_ColCount);
	m_pull = (ResultBind *)malloc(sizeof(ResultBind) * m_ColCount);

	/* Zero data */
	memset(m_bind, 0, sizeof(MYSQL_BIND) * m_ColCount);
	memset(m_pull, 0, sizeof(ResultBind) * m_ColCount);

	m_bUpdatedBinds = false;
}
Exemple #11
0
SQL_RSET SQL_query(const char *query)
{
if(!connected)
return NULL;
if(mysql_query(&nhp_sal_conn,query)==0)
{
MYSQL_RES *mysqlResultSet;
if((mysqlResultSet=mysql_store_result(&nhp_sal_conn)))
{
SQL_RSET res=
(SQL_RSET)malloc(sizeof(struct SQL_RSET_STRUCT));
res->resultSet=mysqlResultSet;
res->index=0;
res->nfields=mysql_num_fields(mysqlResultSet);
res->data=(char **)malloc(sizeof(char *)*res->nfields);
return res;
}
else
return rsetComodin;
}
else
return NULL;
}
Exemple #12
0
        ResultSet::ResultSet(MYSQL* mysql)
        {
            ASSERT(mysql != NULL);
            m_resultSet = mysql_store_result(mysql);
            if(!m_resultSet)
            {
                throw Error(mysql, __FILE__, __LINE__);
            }
			//m_currentRow = mysql_fetch_row(m_resultSet);
			m_numFields = mysql_num_fields(m_resultSet);
			
			for(int i = 0; i < m_numFields; ++i)
			{
                MYSQL_FIELD *field = mysql_fetch_field_direct(m_resultSet,i);
				Column *col = new Column(this, field,i);
				m_columns.push_back(col);
                std::string n = col->ColumnName();
                std::transform(n.begin(),n.end(),n.begin(),tolower);
                m_columnsMap.insert(std::make_pair(n,col));
			}
			
			
        }
Exemple #13
0
void SqlTable::CopyToTable(TTable* _pTable, MYSQL_RES* pRes)
{
	unsigned int nNumFields = mysql_num_fields(pRes);

	TRow vecStrRow(nNumFields);

	MYSQL_ROW Row;

	while ( Row = mysql_fetch_row(pRes) )
	{
		unsigned long *lengths;
		lengths = mysql_fetch_lengths(pRes);

		_pTable->push_back(vecStrRow);

		for(TRow::iterator it = _pTable->back().begin(); it !=  _pTable->back().end(); ++it)
		{
			if ( Row[it - _pTable->back().begin()] != 0 )
				*it = CMyStr(Row[it - _pTable->back().begin()]);
		}
	}

}
Exemple #14
0
//FUNZIONE DI PROVA CHE STAMPA TUTTA LA TABELLA
void DBFetch::stampatutto(MYSQL_RES *res)
{      	// puntatore dei risultati
        MYSQL_ROW row;	// puntatore alla tupla 
        MYSQL_FIELD *field;
        
        printf("\n");
        printf("Database content: \n");
 
        //funzione di stampa dei risultati
        
        unsigned int num_fields;
        unsigned int i;

        num_fields = mysql_num_fields(res);
        
        while ((row = mysql_fetch_row(res)))/*scorre le righe, returna false quando sono finite*/
        {
            for(int i = 0; i < num_fields; i++)
            { 
                printf("%s  ", row[i] ? row[i] : "NULL"); 
            } 
        }       
}
Exemple #15
0
dbResult::dbResult (MYSQL_RES * res)
{
	Rows = 0;
	Fields = 0;
	if (res != NULL)
	{
		Rows = mysql_num_rows(res);
		Fields = mysql_num_fields(res);
		MYSQL_ROW row_buff;
		Row Row_buff;
		if ( Fields != 0) Row_buff.reserve(Fields);
		if ( Rows != 0) Result.reserve(Rows);
		while (( row_buff = mysql_fetch_row(res)))
		{
			for (size_t i = 0; i < Fields; i++)
			{
				if ( row_buff[i] != NULL) 
				{
					Row_buff.push_back(row_buff[i]);
				}
				else
				{
					 Row_buff.push_back("");
				}
			}
			Result.push_back(Row_buff);
			Row_buff.clear();
		}
		MYSQL_FIELD *field;
		if ( Fields != 0) fieldNames.reserve(Fields);
		while((field = mysql_fetch_field(res)))
		{
			fieldNames.push_back(field->name);
		}
	mysql_free_result(res); //clear the result allocation
	}
}
Exemple #16
0
bool sql_conner::sql_select(std::string field_name[],std::string _out_data[][4],int &_out_row)
{
	std::string sql="select * from project ";
	if(mysql_query(mysql_conn,sql.c_str())==0)
	{
		//std::cout<<"<p>query success</p>"<<std::endl;
	}
	else
	{
		//std::cout<<"<p>query failed</p>"<<std::endl;
	}
	res=mysql_store_result(mysql_conn);
	int row_num=mysql_num_rows(res);
	int field_num=mysql_num_fields(res);
	_out_row=row_num;
	MYSQL_FIELD *fd = NULL;
	int i=0;
	for(;fd=mysql_fetch_field(res);)
	{
	//	std::cout<<fd->name<<"\t";
		field_name[i++]=fd->name;
	}
	for(i=0;i<row_num;i++)
	{
		MYSQL_ROW _row = mysql_fetch_row(res);
		if(_row)
		{
			int j=0;
			for(;j<field_num;++j)
			{
				_out_data[i][j]=_row[j];
				//std::cout<<_row[j]<<"\t";
			}
		}
	}
	return true;
}
BOOST_MYSQL_RES mysqldb::select( std::string& query )
{
//	LOG_DEBUG("select query : %s", query.c_str());

	row_count_ = 0;

	MYSQL_RES* p = NULL;
	BOOST_MYSQL_RES ret(p);

	if (mysql_real_query(conn_, query.c_str(), query.length()) == 0)
	{
		ret.reset(mysql_store_result(conn_), mysql_free_result);
		row_count_ = (int)mysql_num_rows(ret.get());
		if (row_count_ > 0)
		{
			// 필드명을 이용하여 std::map을 구성
			field_name_.clear();

			int fieldcount = (int)mysql_num_fields(ret.get());
			for (int i = 0; i < fieldcount; ++i)
			{
				MYSQL_FIELD* fieldinfo = mysql_fetch_field(ret.get());
				field_name_.insert(map_t::value_type(fieldinfo->name, i));
			}
		}
		else
		{
			LOG_INFO("no row : query[%s]", query.c_str());
		}
	}
	else
	{
		LOG_ERROR("query error : query[%s] / error[%s]", query.c_str(), mysql_error(conn_));
	}

	return ret;
}
void
process_result_set (MYSQL *conn, MYSQL_RES *res_set)
{
MYSQL_ROW   row;
MYSQL_FIELD   *field;
unsigned long *length;
unsigned int  i;

  for (i = 0; i < mysql_num_fields (res_set); i++)
  {
    field = mysql_fetch_field (res_set);
    printf ("----- %u -----\n", i);
    printf ("            name: %s\n", field->name);
    printf ("        org_name: %s\n", field->org_name);
    printf ("           table: %s\n", field->table ? field->table : "NULL");
    printf ("       org_table: %s\n", field->org_table);
    printf ("              db: %s\n", field->db);
    printf ("         catalog: %s\n", field->catalog);
    printf ("             def: %s\n", field->def ? field->def : "NULL");
    printf ("          length: %lu\n", field->length);
    printf ("      max_length: %lu\n", field->max_length);
    printf ("     name_length: %u\n", field->name_length);
    printf (" org_name_length: %u\n", field->org_name_length);
    printf ("    table_length: %u\n", field->table_length);
    printf ("org_table_length: %u\n", field->org_table_length);
    printf ("       db_length: %u\n", field->db_length);
    printf ("   catalog_length: %u\n", field->catalog_length);
    printf ("       def_length: %u\n", field->def_length);
    printf ("            flags: %x\n", field->flags);
    printf ("         decimals: %u\n", field->decimals);
    printf ("        charsetnr: %u\n", field->charsetnr);
    printf ("             type: %u\n", field->type);
    printf ("           IS_NUM: %d\n", IS_NUM(field->type));
    printf ("      IS_NOT_NULL: %d\n", IS_NOT_NULL(field->flags));
  }
}
Exemple #19
0
bool Mysql::saveSelectResult(MysqlResult *result)
{
	unsigned int i;
	unsigned int fieldCount;
	MYSQL_FIELD *field;

	// 保存结果集
	result->res = mysql_store_result( this->db );
	if ( result->res == NULL )
	{
		this->markLastError();
		return false;
	}

	// 建立索引
	fieldCount = mysql_num_fields( result->res );
	field = mysql_fetch_fields( result->res );
	for (i=0; i<fieldCount; i++)
	{
		result->fieldMap[ field[i].name ] = i;		
	}

	return true;
}
Exemple #20
0
		bool MysqlInterface::Select(const char* sqlstr, db_callback callback, void* output)
		{
			if(mysql_real_query(&mysql, sqlstr, strlen(sqlstr))!=0)
				return false;
			
			res = mysql_store_result(&mysql);
			
			if(res==nullptr)
				return false;

			if(callback)
			{
				int field_count=mysql_num_fields(res);

				while(row = mysql_fetch_row(res))
				{
					callback(row,field_count,output);
				}
			}
			
			mysql_free_result(res);

			return true;
		}
Exemple #21
0
vector<string> CMySQLQuery :: nextRow( )
{
	vector<string> vecReturn;

	if( m_pRes )
	{
		MYSQL_ROW row;

		unsigned int num_fields = mysql_num_fields( m_pRes );
		unsigned int i;

		vecReturn.reserve( num_fields );

		if( row = mysql_fetch_row( m_pRes ) )
		{
			unsigned long *lengths = mysql_fetch_lengths( m_pRes );

			for( i = 0; i < num_fields; i++ )
				vecReturn.push_back( string( row[i], lengths[i] ) );
		}
	}

	return vecReturn;
}
Exemple #22
0
/*
 * column_names = statement:columns()
 */
static int statement_columns(lua_State *L) {
    statement_t *statement = (statement_t *)luaL_checkudata(L, 1, DBD_MYSQL_STATEMENT);

    MYSQL_FIELD *fields;
    int i;
    int num_columns;
    int d = 1;

    if (!statement->stmt) {
        luaL_error(L, DBI_ERR_INVALID_STATEMENT);
        return 0;
    }

    fields = mysql_fetch_fields(statement->metadata);
    num_columns = mysql_num_fields(statement->metadata);
    lua_newtable(L);
    for (i = 0; i < num_columns; i++) {
	const char *name = fields[i].name;

        LUA_PUSH_ARRAY_STRING(d, name);
    }

    return 1;
}
Exemple #23
0
void schauspieler_suchen(char *name) {
   unsigned long  anzahl_reihen;
   unsigned int i;
   MYSQL_ROW  row;
   MYSQL_RES  *mysql_res;

   char *query, *string;
   char *select = "SELECT * FROM filmdaten WHERE hauptrolle='";
   string = malloc(strlen(name)+2);
   strcpy(string,name);
   strcat(string, "'");
   query = malloc(strlen(select)+strlen(string)+1);
   strcpy(query, select);
   strcat(query, string);

   /* jetzt die Anfrage an den Datenbankserver */
   mysql_real_query(mysql, query, strlen(query));
   check_error();
   /* Daten der Anfrage abholen */
   mysql_res = mysql_store_result(mysql);
   check_error();
   /* Anzahl der gefundenen Datensätze ermitteln */
   anzahl_reihen = (unsigned long) mysql_num_rows (mysql_res);
   printf ("Anzahl gefunden: %lu\n\n", anzahl_reihen);
   /* gefundenen Datensatz bzw. Datensätze ausgeben */
   while ((row = mysql_fetch_row (mysql_res)) != NULL) {
      /* Einzelne Spalten der Zeile ausgeben */
      for (i = 0;  i < mysql_num_fields(mysql_res);  i ++)
         printf ("%s ",row[i]);
      printf("\n");
   }
   /* Speicherplatz wieder freigeben */
   mysql_free_result(mysql_res);
   free(string);
   free(query);
}
Exemple #24
0
/* prints results in a tabular form */
void printres(MYSQL_RES *result) {
  char           *place;
  int             nrows;
  unsigned int      i,j;
  unsigned int num_fields;
  unsigned long *lengths;

  nrows = mysql_num_rows(result);
  if (nrows == 0) {
    printf("No entries for %s\n", place);
  } else {
    MYSQL_ROW       row;
    for (i = 0; i < nrows; i++) {
      row = mysql_fetch_row(result);
      num_fields = mysql_num_fields(result);
      lengths = mysql_fetch_lengths(result);

      for (j = 0; j < num_fields; j++)
	printf("\t%s", row[j]);
      printf("\n");
    }
    printf("\n");
  }
}
string Database::get(string field, int line) {
    //cout << "get2: "<<field<<endl;
    int pos=-1;
    int cols = mysql_num_fields(qry);
    int lines = get_num_rows();

    fields = mysql_fetch_fields(qry);
	//cout << "lines "<< lines<<" erro "<<getError()<<endl;
    if (line <= lines) {

        for(int i=0;i<= (cols-1);++i){
            if (fields[i].name == field) {
               pos = i;
               break;
            }
        }
        mysql_data_seek(qry,line-1);
        return mysql_fetch_row(qry)[pos];

    } else {
	    return "";
    }

}
Exemple #26
0
void dump_mysql_result(MYSQL_RES * result)
{
   MYSQL_ROW row;
   MYSQL_FIELD * fields = mysql_fetch_fields(result);
   word num_fields = mysql_num_fields(result);
   word num_rows   = mysql_num_rows(result);
   word field, row_i;
   char zs[1024];

   sprintf(zs, "Result dump: %d rows of %d fields", num_rows, num_fields); _log(MINOR, zs);

   for(row_i = 0; row_i < num_rows; row_i++)
   {
      sprintf(zs, "Row %d", row_i);
      _log(MINOR, zs);
      
      row = mysql_fetch_row(result);
      for(field = 0; field < num_fields; field++)
      {
         sprintf(zs, "   %s = \"%s\"", fields[field].name, row[field]); 
         // See if we can spot a timestamp
         if(row[field][0] == '1' && strlen(row[field]) == 10)
         {
            time_t stamp = atol(row[field]);
            // Accept    Jan 2008      to      May 2033
            //        1,200,000,000         2,000,000,000
            if(stamp > 1200000000L && stamp < 2000000000L)
            {
               strcat(zs, "  ");
               strcat(zs, time_text(stamp, false ));
            }
         }               
         _log(MINOR, zs);
      }
   }
} 
Exemple #27
0
int wsql_result__init__(wsql_result *self, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = {"connection", "use", NULL};
    MYSQL_RES *result;
    wsql_connection *connection = NULL;
    int use = 0;
    unsigned int n;

    TRACE1("%p", self);

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i", kwlist, &connection, &use))
        return -1;

    Py_BEGIN_ALLOW_THREADS ;
    result = use ? mysql_use_result(&(connection->connection)) : mysql_store_result(&(connection->connection));
    self->result = result;
    self->more_rows = result ? 1 : 0;
    self->use = use;
    Py_END_ALLOW_THREADS;

    self->connection = (PyObject *) connection;
    Py_INCREF(self->connection);

    if (!result)
    {
        if (mysql_field_count(&(connection->connection)) == 0)
            return 0;

        wsql_raise_error(connection);
        return -1;
    }
    n = mysql_num_fields(result);
    self->num_fields = n;
    self->fields = wsql_result_get_fields(self, n);
    return 0;
}
Exemple #28
0
void
vPrintResult(MYSQL_RES **res, MYSQL_ROW *row) {

    unsigned long iNumRows = (unsigned long) mysql_num_rows(*res);
    unsigned int iColumns = mysql_num_fields(*res);
    MYSQL_FIELD *lpField;
    int i, j;

    printf("Have %ld rows are fetched, as following: \n", iNumRows);

    for(i = 1, *row = mysql_fetch_row(*res); *row != NULL; *row = mysql_fetch_row(*res), i ++) {
        printf("---The row %d:\n", i);

        for(j = 0; j < iColumns; j ++) {
            lpField = mysql_fetch_field_direct(*res, j);

            printf("Field %s: %s\n", lpField->name, (*row)[j]);
        }

        printf("\n");
    }

    mysql_free_result(*res);
}
Exemple #29
0
map<string, vector<string>> DBWrapper::getData(vector<string> *field, map<string, vector<string>> container, const char* query){
	MYSQL_RES *res;
	MYSQL_ROW row;
	mysql_query(&mysql, query);
	res = mysql_store_result(&mysql);
	int count = mysql_num_fields(res);

	while(row=mysql_fetch_row(res)){
		
		for(unsigned int i = 0 ; i < field->size() ; i++)
		{
			if(row[i]==NULL)
			{
				container[field->at(i)].push_back("");
			}else{
				container[field->at(i)].push_back(row[i]);
			}
			
		}
	}

	mysql_free_result(res);
	return container;
}
bool CMySQLController::SelectQuery(const char* strQuery)
{
	try{
		int state = mysql_query(&m_Connection, strQuery);
		if (state != 0)
		{
			printf(mysql_error(&m_Connection));
			return false;
		}
		m_pResult = mysql_store_result(&m_Connection);
		m_iNumFields = mysql_num_fields(m_pResult);
		m_pFields = mysql_fetch_fields(m_pResult);
		return true;
	}
	catch (exception& ex)
	{
		string strLog;
		stringstream strErrorMess;
		strErrorMess << ex.what() << "][" << __FILE__ << "|" << __LINE__;
		strLog = CUtilities::FormatLog(ERROR_MSG, "CMySQLController", "Find", "exception:" + strErrorMess.str());
		CUtilities::WriteErrorLog(ERROR_MSG, strLog);
		return false;
	}
}