예제 #1
0
파일: pg_encode.c 프로젝트: Dasudian/otp
void encode_result(ei_x_buff* x, PGresult* res, PGconn* conn)
{
    int row, n_rows, col, n_cols;
    switch (PQresultStatus(res)) {
    case PGRES_TUPLES_OK: 
	n_rows = PQntuples(res); 
	n_cols = PQnfields(res); 
	ei_x_encode_tuple_header(x, 2);
	encode_ok(x);
	ei_x_encode_list_header(x, n_rows+1);
 	ei_x_encode_list_header(x, n_cols);
	for (col = 0; col < n_cols; ++col) {
	    ei_x_encode_string(x, PQfname(res, col));
	}
	ei_x_encode_empty_list(x); 
	for (row = 0; row < n_rows; ++row) {
	    ei_x_encode_list_header(x, n_cols);
	    for (col = 0; col < n_cols; ++col) {
		ei_x_encode_string(x, PQgetvalue(res, row, col));
	    }
	    ei_x_encode_empty_list(x);
	}
	ei_x_encode_empty_list(x); 
	break; 
    case PGRES_COMMAND_OK:
	ei_x_encode_tuple_header(x, 2);
        encode_ok(x);
	ei_x_encode_string(x, PQcmdTuples(res));
        break;
    default:
	encode_error(x, conn);
	break;
    }
}
예제 #2
0
const char *PostgresqlResultSet_getColumnName(T R, int columnIndex) {
        assert(R);
        columnIndex--;
        if (R->columnCount <= 0 || columnIndex < 0 || columnIndex > R->columnCount)
                return NULL;
        return PQfname(R->res, columnIndex);
}
예제 #3
0
void ResultSet::init(PGresult* res)
{
	int nFields													= PQnfields(res);

	for (int i = 0; i < nFields; i = i + 1)						{ this->columns.push_back(PQfname(res, i)); }

	int nTuples													= PQntuples(res);
	std::vector<std::string*>* v;
	char* value;

	for (int i = 0; i < nTuples; i = i + 1)
	{
		v														= new std::vector<std::string*>();

		for (int j = 0; j < nFields; j++)
		{
			if (PQgetisnull(res, i, j))							{ v->push_back(nullptr); }
			else
			{
				value											= PQgetvalue(res, i, j);

				v->push_back(new std::string(value, PQgetlength(res, i, j)));
			}
		}

		this->rows.push_back(v);
	}
}
예제 #4
0
PgSQLResult::PgSQLResult(PgSQLConnection* pConnection, PGresult * sqlResult)
    : KCSQLResultBase(pConnection)
{
    m_sqlResult = sqlResult;
    if (m_sqlResult)
    {
        m_numRows = PQntuples(m_sqlResult);
        m_numFields = PQnfields(m_sqlResult);
        m_sqlRow = -1;

        for (int i = 0; i<m_numFields; ++i)
        {
            m_vName.push_back( PQfname(m_sqlResult, i) );
        }
        m_vValue.resize(m_numFields);
        const char* pszResult = PQcmdTuples(sqlResult);
        if (pszResult)
        {
            m_affectRowCount = atoi(pszResult);
        }
        Seek(0);
    }
    else
    {
        m_sqlRow = -1;
        m_numRows = 0;
        m_numFields = 0;
    }
}
예제 #5
0
void doSQL(PGconn *conn, char *command){
	PGresult *result;
	printf("%s\n", command);
	result = PQexec(conn, command);
	printf("Result message: %s\n", PQresultErrorMessage(result));	
	
	switch(PQresultStatus(result)) {
		case PGRES_TUPLES_OK:{
			int n = 0, m = 0;
			int nrows   = PQntuples(result);
			int nfields = PQnfields(result);
			for(m = 0; m < nrows; m++) {
				for(n = 0; n < nfields; n++)
					printf(" %s = %s", PQfname(result, n),PQgetvalue(result,m,n));
				printf("\n");
      			}

			if(nrows == 0 || nfields == 0){
				printf("Car does not exist in database!");
				searchT = 0;
			}
		}
	}

	PQclear(result);
}
예제 #6
0
bool DataLayer::find(string table, string search_by_attr, string attr_value, vector<map<string, string> >& search_results, string joins){
	string query;
	search_results.clear(); // reset the results
	if(joins == "false"){
		query = "SELECT * FROM " + table + " WHERE " + search_by_attr + " ~* '" + attr_value + "';";
	} else {
		// making this less abstracted than originally planned, since I only use it for one purpose
		query = "SELECT * FROM " + table + " INNER JOIN " + joins + " ON (accounts.client_id = clients.id) WHERE " + search_by_attr + " ~* '" + attr_value + "';";
	}
	PGresult* res = PQexec(conn, query.c_str());
	if(PQresultStatus(res) == PGRES_TUPLES_OK && PQntuples(res) > 0){

		for(int i = 0; i < PQntuples(res); i++){
			map<string, string> row;
			for(int j = 0; j < PQnfields(res); j++){
			  row[PQfname(res, j)] = PQgetvalue(res, i, j);
		  }
			search_results.push_back(row);
			row.clear();

		}
		return true;
	}
	return false;
}
예제 #7
0
파일: pgBook.cpp 프로젝트: Fabel/pgsql
vector<Author> pgBook::authorsFor(Book book)
{
	string sql = where("authors", book.authorsCondition());
	PGresult *result = driver->selectsDataSQL(sql);
	data itemAttributes;
	vector<Author> authors;
	int rows = PQntuples(result);
	if(rows)
	{
		for(int j=0;j<rows;j++)
		{
			for (int i=0; i<PQnfields(result); i++)
			{
				itemAttributes[PQfname(result, i)] = PQgetvalue(result, j, i);
			}
			Author item(itemAttributes);
			authors.push_back(item);
		}
		PQclear(result);
	}
	else
	{
		cout<<"Authors don\'t exist!"<<endl;
	}
	return authors;
}
예제 #8
0
wxString PgStatement::GetFieldName(int nIndex)
  {
  char * szName = PQfname(pgr, nIndex);
	wxString sName = wxString::FromAscii(szName);

  return sName;
  }
예제 #9
0
   int 
   PGRecordset::GetColumnIndex_(const AnsiString &sColumnName) const
   //---------------------------------------------------------------------------()
   // DESCRIPTION:
   // Returns the index of a column in the recordset, based on the columns name.
   //---------------------------------------------------------------------------()
   {
      if (!result_)
      {
         // Result set wasn't initialized. Shouldn't happen.
         ErrorManager::Instance()->ReportError(HM::ErrorManager::High, 5093, "PGConnection::Close", "An unknown error occurred while closing recordset.");
         return 0;
      }

      unsigned int iFieldCount = PQnfields(result_);

      for (unsigned int i = 0; i <= iFieldCount; i++)
      {
         AnsiString sColName = PQfname(result_, i);

         if (sColName == sColumnName)
            return i;

      }      

      // Result set wasn't initialized. Shouldn't happen.
      ErrorManager::Instance()->ReportError(ErrorManager::High, 5092, "MySQLRecordset::GetColumnIndex_", "The requested column was not found. Column name: " + sColumnName);

      return -1;
   }
예제 #10
0
static void postgres_ingest_stats(postgres_check_info_t *ci) {
  if(ci->rv == PGRES_TUPLES_OK) {
    /* metrics */
    int nrows, ncols, i, j;
    nrows = PQntuples(ci->result);
    ncols = PQnfields(ci->result);
    noit_stats_set_metric(&ci->current, "row_count", METRIC_INT32, &nrows);
    for (i=0; i<nrows; i++) {
      noitL(nldeb, "postgres: row %d [%d cols]:\n", i, ncols);
      if(ncols<2) continue;
      if(PQgetisnull(ci->result, i, 0)) continue;
      for (j=1; j<ncols; j++) {
        Oid coltype;
        int iv, *piv;
        int64_t lv, *plv;
        double dv, *pdv;
        char *sv;
        char mname[128];
  
        snprintf(mname, sizeof(mname), "%s`%s",
                 PQgetvalue(ci->result, i, 0), PQfname(ci->result, j));
        coltype = PQftype(ci->result, j);
        noitL(nldeb, "postgres:   col %d (%s) type %d:\n", j, mname, coltype);
        switch(coltype) {
          case BOOLOID:
            if(PQgetisnull(ci->result, i, j)) piv = NULL;
            else {
              iv = strcmp(PQgetvalue(ci->result, i, j), "f") ? 1 : 0;
              piv = &iv;
            }
            noit_stats_set_metric(&ci->current, mname, METRIC_INT32, piv);
            break;
          case INT2OID:
          case INT4OID:
          case INT8OID:
            if(PQgetisnull(ci->result, i, j)) plv = NULL;
            else {
              lv = strtoll(PQgetvalue(ci->result, i, j), NULL, 10);
              plv = &lv;
            }
            noit_stats_set_metric(&ci->current, mname, METRIC_INT64, plv);
          case FLOAT4OID:
          case FLOAT8OID:
          case NUMERICOID:
            if(PQgetisnull(ci->result, i, j)) pdv = NULL;
            else {
              dv = atof(PQgetvalue(ci->result, i, j));
              pdv = &dv;
            }
            noit_stats_set_metric(&ci->current, mname, METRIC_DOUBLE, pdv);
          default:
            if(PQgetisnull(ci->result, i, j)) sv = NULL;
            else sv = PQgetvalue(ci->result, i, j);
            noit_stats_set_metric(&ci->current, mname, METRIC_GUESS, sv);
            break;
        }
      }
    }
  }
}
예제 #11
0
std::string PgsqlReaderProvider::get_column_name(int index) const
{
	const char *const string = PQfname(result, index);
	if (string == nullptr)
		throw ("Index out of range");
	return std::string(string);
}
예제 #12
0
static int pgsql_stmt_describe(pdo_stmt_t *stmt, int colno)
{
	pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
	struct pdo_column_data *cols = stmt->columns;
	struct pdo_bound_param_data *param;
	char *str;

	if (!S->result) {
		return 0;
	}

	str = PQfname(S->result, colno);
	cols[colno].name = zend_string_init(str, strlen(str), 0);
	cols[colno].maxlen = PQfsize(S->result, colno);
	cols[colno].precision = PQfmod(S->result, colno);
	S->cols[colno].pgsql_type = PQftype(S->result, colno);

	switch (S->cols[colno].pgsql_type) {

		case BOOLOID:
			cols[colno].param_type = PDO_PARAM_BOOL;
			break;

		case OIDOID:
			/* did the user bind the column as a LOB ? */
			if (stmt->bound_columns && (
					(param = zend_hash_index_find_ptr(stmt->bound_columns, colno)) != NULL ||
					(param = zend_hash_find_ptr(stmt->bound_columns, cols[colno].name)) != NULL)) {

				if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
					cols[colno].param_type = PDO_PARAM_LOB;
					break;
				}
			}
			cols[colno].param_type = PDO_PARAM_INT;
			break;

		case INT2OID:
		case INT4OID:
			cols[colno].param_type = PDO_PARAM_INT;
			break;

		case INT8OID:
			if (sizeof(zend_long)>=8) {
				cols[colno].param_type = PDO_PARAM_INT;
			} else {
				cols[colno].param_type = PDO_PARAM_STR;
			}
			break;

		case BYTEAOID:
			cols[colno].param_type = PDO_PARAM_LOB;
			break;

		default:
			cols[colno].param_type = PDO_PARAM_STR;
	}

	return 1;
}
예제 #13
0
 string column::name() const
 {
     if (!is_valid()) {
         return string();
     }
     return PQfname(stmt_.get(), column_);
 }
예제 #14
0
파일: select1.c 프로젝트: swistak/skarbnik
void doSQL(PGconn *conn, char *command)
{
  PGresult *result;

  printf("%s\n", command);

  result = PQexec(conn, command);
  printf("status is %s\n", PQresStatus(PQresultStatus(result)));
  printf("#rows affected %s\n", PQcmdTuples(result));
  printf("result message: %s\n", PQresultErrorMessage(result));

  switch(PQresultStatus(result)) {
  case PGRES_TUPLES_OK:
    {
      int r, n;
      int nrows = PQntuples(result);
      int nfields = PQnfields(result);
      printf("number of rows returned = %d\n", nrows);
      printf("number of fields returned = %d\n", nfields);
      for(r = 0; r < nrows; r++) {
	for(n = 0; n < nfields; n++)
	  printf(" %s = %s(%d),", 
		 PQfname(result, n), 
		 PQgetvalue(result, r, n),
		 // rozmiar pola w bajtach
		 PQgetlength(result, r, n));
	printf("\n");
      }
    }
  }
  PQclear(result);
}
예제 #15
0
파일: psql.c 프로젝트: aosm/X11
LispObj *
Lisp_PQfname(LispBuiltin *builtin)
/*
 pq-fname result field-number
 */
{
    char *string;
    int field;
    PGresult *res;

    LispObj *result, *field_number;

    field_number = ARGUMENT(1);
    result = ARGUMENT(0);

    if (!CHECKO(result, PGresult_t))
	LispDestroy("%s: cannot convert %s to PGresult*",
		    STRFUN(builtin), STROBJ(result));
    res = (PGresult*)(result->data.opaque.data);

    CHECK_INDEX(field_number);
    field = FIXNUM_VALUE(field_number);

    string = PQfname(res, field);

    return (string ? STRING(string) : NIL);
}
예제 #16
0
/**********************************
 * execute_put_values

 Put the values of one tuple into Tcl variables named like the
 column names, or into an array indexed by the column names.
 **********************************/
static int
execute_put_values(Tcl_Interp *interp, CONST84 char *array_varname,
				   PGresult *result, int tupno)
{
	int			i;
	int			n;
	char	   *fname;
	char	   *value;

	/*
	 * For each column get the column name and value and put it into a Tcl
	 * variable (either scalar or array item)
	 */
	n = PQnfields(result);
	for (i = 0; i < n; i++)
	{
		fname = PQfname(result, i);
		value = PQgetvalue(result, tupno, i);

		if (array_varname != NULL)
		{
			if (Tcl_SetVar2(interp, array_varname, fname, value,
							TCL_LEAVE_ERR_MSG) == NULL)
				return TCL_ERROR;
		}
		else
		{
			if (Tcl_SetVar(interp, fname, value, TCL_LEAVE_ERR_MSG) == NULL)
				return TCL_ERROR;
		}
	}

	return TCL_OK;
}
예제 #17
0
Row::Row(PGresult *exec_result, int row) {
  int field_count = PQnfields( exec_result );
  for(int column = 0; column < field_count; ++column) {
    string name = PQfname(exec_result, column);
    attributes_[name] = Attribute::from_field(exec_result, row, column);
  }
}
예제 #18
0
static VALUE cCommand_execute_reader(int argc, VALUE *argv[], VALUE self) {
  VALUE reader, query;
  VALUE field_names, field_types;

  int i;
  int field_count;
  int infer_types = 0;

  VALUE connection = rb_iv_get(self, "@connection");
  VALUE postgres_connection = rb_iv_get(connection, "@connection");
  if (Qnil == postgres_connection) {
    rb_raise(eConnectionError, "This connection has already been closed.");
  }

  PGconn *db = DATA_PTR(postgres_connection);
  PGresult *response;

  query = build_query_from_args(self, argc, argv);

  response = cCommand_execute(self, db, query);

  if ( PQresultStatus(response) != PGRES_TUPLES_OK ) {
    raise_error(self, response, query);
  }

  field_count = PQnfields(response);

  reader = rb_funcall(cReader, ID_NEW, 0);
  rb_iv_set(reader, "@connection", connection);
  rb_iv_set(reader, "@reader", Data_Wrap_Struct(rb_cObject, 0, 0, response));
  rb_iv_set(reader, "@field_count", INT2NUM(field_count));
  rb_iv_set(reader, "@row_count", INT2NUM(PQntuples(response)));

  field_names = rb_ary_new();
  field_types = rb_iv_get(self, "@field_types");

  if ( field_types == Qnil || 0 == RARRAY_LEN(field_types) ) {
    field_types = rb_ary_new();
    infer_types = 1;
  } else if (RARRAY_LEN(field_types) != field_count) {
    // Whoops...  wrong number of types passed to set_types.  Close the reader and raise
    // and error
    rb_funcall(reader, rb_intern("close"), 0);
    rb_raise(eArgumentError, "Field-count mismatch. Expected %ld fields, but the query yielded %d", RARRAY_LEN(field_types), field_count);
  }

  for ( i = 0; i < field_count; i++ ) {
    rb_ary_push(field_names, rb_str_new2(PQfname(response, i)));
    if ( infer_types == 1 ) {
      rb_ary_push(field_types, infer_ruby_type(PQftype(response, i)));
    }
  }

  rb_iv_set(reader, "@position", INT2NUM(0));
  rb_iv_set(reader, "@fields", field_names);
  rb_iv_set(reader, "@field_types", field_types);

  return reader;
}
예제 #19
0
OGRPGResultLayer::OGRPGResultLayer( OGRPGDataSource *poDSIn, 
                                    const char * pszRawQueryIn,
                                    PGresult *hInitialResultIn )
{
    poDS = poDSIn;

    iNextShapeId = 0;

    pszRawStatement = CPLStrdup(pszRawQueryIn);

    osWHERE = "";

    BuildFullQueryStatement();

    ReadResultDefinition(hInitialResultIn);

    pszGeomTableName = NULL;
    pszGeomTableSchemaName = NULL;

    /* Find at which index the geometry column is */
    int iGeomCol = -1;
    if (poFeatureDefn->GetGeomFieldCount() == 1)
    {
        int iRawField;
        for( iRawField = 0; iRawField < PQnfields(hInitialResultIn); iRawField++ )
        {
            if( strcmp(PQfname(hInitialResultIn,iRawField),
                    poFeatureDefn->GetGeomFieldDefn(0)->GetNameRef()) == 0 )
            {
                iGeomCol = iRawField;
                break;
            }
        }
    }

#ifndef PG_PRE74
    /* Determine the table from which the geometry column is extracted */
    if (iGeomCol != -1)
    {
        Oid tableOID = PQftable(hInitialResultIn, iGeomCol);
        if (tableOID != InvalidOid)
        {
            CPLString osGetTableName;
            osGetTableName.Printf("SELECT c.relname, n.nspname FROM pg_class c "
                                  "JOIN pg_namespace n ON c.relnamespace=n.oid WHERE c.oid = %d ", tableOID);
            PGresult* hTableNameResult = OGRPG_PQexec(poDS->GetPGConn(), osGetTableName );
            if( hTableNameResult && PQresultStatus(hTableNameResult) == PGRES_TUPLES_OK)
            {
                if ( PQntuples(hTableNameResult) > 0 )
                {
                    pszGeomTableName = CPLStrdup(PQgetvalue(hTableNameResult,0,0));
                    pszGeomTableSchemaName = CPLStrdup(PQgetvalue(hTableNameResult,0,1));
                }
            }
            OGRPGClearResult( hTableNameResult );
        }
    }
#endif
}
예제 #20
0
파일: row.cpp 프로젝트: ryjen/db
            string row::column_name(size_t nPosition) const
            {
                if (nPosition >= size()) {
                    throw no_such_column_exception();
                }

                return PQfname(stmt_.get(), nPosition);
            }
예제 #21
0
	void GetCols(std::vector<std::string>& result)
	{
		result.resize(PQnfields(res));
		for(unsigned int i=0; i < result.size(); i++)
		{
			result[i] = PQfname(res, i);
		}
	}
예제 #22
0
파일: be.c 프로젝트: po1vo/aide
static int be_sql_readinit(psql_data* ret) {
  /* Yes.. we don't want to know about two first result.. 
     and we want no memoryleaking.
  */
  int i,j,nFields;
  char* s;
  char declare []="DECLARE aidecursor CURSOR FOR select * from ";
  
  s = (char*)malloc(strlen(declare)+strlen(ret->table)+1);
  s[0]=0;
  s=strcat(s,declare);
  s=strcat(s,ret->table);
  
  ret->res=PQexec(ret->conn,s);
		  
  if (!ret->res || PQresultStatus(ret->res) != PGRES_COMMAND_OK) {
    
    if (ret->res!=NULL) {
      error(255,"Psql error: %s\n",PQresStatus(PQresultStatus(ret->res)));
      PQclear(ret->res);
    }
    return RETFAIL;
  }
  PQclear(ret->res);
  
  ret -> res = PQexec(ret->conn, "FETCH ALL in aidecursor");
  
  if (!ret->res || PQresultStatus(ret->res) != PGRES_TUPLES_OK)
    {
      error(0, "FETCH ALL command didn't return tuples properly\n");
      PQclear(ret->res);
      abort();
    }
  
  
  /* first, print out the attribute names */
  nFields = PQnfields(ret->res);
  for (i = 0; i < nFields; i++)
    error(255,"%-15s", PQfname(ret->res, i));
  error(255,"\n\n");
  
  
  for(i=0;i<db_unknown;i++){
    ret->des[i]=PQfnumber(ret->res,db_names[i]);
    if (ret->des[i]!=-1) {
      error(255,"Field %i,%s \n",ret->des[i],db_names[i]);
    }
  }
  
  ret->curread=0;
  ret->maxread=PQntuples(ret->res);
  /* And now we know how many fields we have.. */
  
  error(10,"%i tuples\n",ret->maxread);
  
  return RETOK;
  
}
예제 #23
0
/*
 *	Read in field descriptions from a libpq result set.
 *	If self is not null, then also store the information.
 *	If self is null, then just read, don't store.
 */
BOOL
CI_read_fields_from_pgres(ColumnInfoClass *self, PGresult *pgres)
{
	CSTR		func = "CI_read_fields";
	Int2		lf;
	int			new_num_fields;
	OID		new_adtid, new_relid = 0, new_attid = 0;
	Int2		new_adtsize;
	Int4		new_atttypmod = -1;
	char	   *new_field_name;

	/* at first read in the number of fields that are in the query */
	new_num_fields = PQnfields(pgres);

	mylog("num_fields = %d\n", new_num_fields);

	if (self)
	{
		/* according to that allocate memory */
		CI_set_num_fields(self, new_num_fields);
		if (NULL == self->coli_array)
			return FALSE;
	}

	/* now read in the descriptions */
	for (lf = 0; lf < new_num_fields; lf++)
	{
		new_field_name = PQfname(pgres, lf);
		new_relid = PQftable(pgres, lf);
		new_attid = PQftablecol(pgres, lf);
		new_adtid = PQftype(pgres, lf);
		new_adtsize = PQfsize(pgres, lf);

		mylog("READING ATTTYPMOD\n");
		new_atttypmod = PQfmod(pgres, lf);

		/* Subtract the header length */
		switch (new_adtid)
		{
			case PG_TYPE_DATETIME:
			case PG_TYPE_TIMESTAMP_NO_TMZONE:
			case PG_TYPE_TIME:
			case PG_TYPE_TIME_WITH_TMZONE:
				break;
			default:
				new_atttypmod -= 4;
		}
		if (new_atttypmod < 0)
			new_atttypmod = -1;

		mylog("%s: fieldname='%s', adtid=%d, adtsize=%d, atttypmod=%d (rel,att)=(%d,%d)\n", func, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid);

		if (self)
			CI_set_field_info(self, lf, new_field_name, new_adtid, new_adtsize, new_atttypmod, new_relid, new_attid);
	}

	return TRUE;
}
예제 #24
0
파일: pgmquery.c 프로젝트: Torvus/pgmanager
gchar*
pgm_query_get_column_name( PgmQuery *query, gint column_number )
{
	g_return_val_if_fail( query != NULL, NULL );
	g_return_val_if_fail( column_number >= 0, NULL );
	g_return_val_if_fail( column_number < pgm_query_get_columns( query ), NULL );

	return PQfname( query->result, column_number );
}
예제 #25
0
QString ResultSet::getColumnName(int column_idx)
{
	//Throws an error in case the column index is invalid
	if(column_idx < 0 || column_idx >= getColumnCount())
		throw Exception(ERR_REF_TUPLE_COL_INV_INDEX, __PRETTY_FUNCTION__, __FILE__, __LINE__);

	//Returns the column name on the specified index
	return(QString(PQfname(sql_result, column_idx)));
}
예제 #26
0
/*
** Creates the list of fields names and pushes it on top of the stack.
*/
static void create_colnames (lua_State *L, cur_data *cur) {
	PGresult *result = cur->pg_res;
	int i;
	lua_newtable (L);
	for (i = 1; i <= cur->numcols; i++) {
		lua_pushstring (L, PQfname (result, i-1));
		lua_rawseti (L, -2, i);
	}
}
예제 #27
0
static const char *dbd_pgsql_get_name(const apr_dbd_results_t *res, int n)
{
    if (res->res) {
        if ((n>=0) && (PQnfields(res->res) > n)) {
            return PQfname(res->res,n);
        }
    }
    return NULL;
}
예제 #28
0
int SPostgres::Retrieve(SString sql,SRecordset &rs)
{
	LOGBASEDEBUG("into SPostgres::Retrieve(%s)",sql.data());
	sql = sql.replace("\\","\\\\");//postgres数据库SQL中\为转义符
	if(m_pConn == NULL)
	{
		LOGWARN("m_pConn is NULL is SPostgres::Retrieve, Connect it at first!");
		Connect();
		if(m_pConn == NULL)
		{
			LOGWARN("m_pConn is NULL is SPostgres::Retrieve, Connect error!");
			return -1;
		}
	}
	PGresult *pRes = PQexec(m_pConn,sql.data());
	if(PQresultStatus(pRes) != PGRES_TUPLES_OK)
	{
		if(pRes != NULL)
			PQclear(pRes);
		if(TestConnect() == true)//连接可用
			return -1;
		//连接不可用自动重连一次数据库
		if(!Reconnect())
			return -2;//连接失败
		pRes = PQexec(m_pConn,sql.data());
		if(PQresultStatus(pRes) != PGRES_TUPLES_OK) 
		{
			if(pRes != NULL)
				PQclear(pRes);
			return -1;
		}
	}

	int cols = PQnfields(pRes);
	int rows = PQntuples(pRes);
	int i,j;
	SRecord *pRecord;
	//写入记录集
	rs.clear();
	rs.SetSize(rows,cols);
	for(i=0;i<cols;i++)
	{
		rs.SetColumnName(i,PQfname(pRes,i));
	}
	for(i=0;i<rows;i++)
	{
		pRecord = rs.GetRecord(i);
		for(j=0;j<cols;j++)
		{
			pRecord->SetValue(j,PQgetvalue(pRes,i,j));
		}
	}
	PQclear(pRes);
	
	return rows;
}
void ctlResultGrid::fillGrid( PGresult * result )
{
    int    rowCount = PQntuples( result );
    int    colCount = PQnfields( result );

    // If this PGresult represents a non-query command 
    // (like an INSERT), there won't be any columns in 
    // the result set - just return

    if( colCount == 0 )
        return;

    // Disable repaints to we don't flicker too much

    BeginBatch();

    // Clear out the old results (if any) and resize 
    // grid to match the result set

    if( GetNumberRows())
        DeleteRows( 0, GetNumberRows());
    if( GetNumberCols())
        DeleteCols( 0, GetNumberCols());

    AppendRows( rowCount );
    AppendCols( colCount );

    EnableEditing( false );

    // Copy the column names from the result set into the column headers

    for( int col = 0; col < colCount; ++col )
        SetColLabelValue( col, wxString( PQfname( result, col ), wxConvUTF8 ));

    // Now copy each value from the result set into the grid

    for( int row = 0; row < rowCount; ++row )
    {
        for( int col = 0; col < colCount; ++col )
        {
            if( PQgetisnull( result, row, col ))
                SetCellValue( row, col, wxT( "" ));
            else
                SetCellValue( row, col, wxString( PQgetvalue( result, row, col ), wxConvUTF8 ));
        }
    }

    // Resize each column to fit its content

    AutoSizeColumns( false );

    // Enable repaints

    EndBatch();
}
예제 #30
0
파일: pgsql.c 프로젝트: gvlx/gawkextlib
static awk_value_t *
do_pg_getrowbyname(int nargs, awk_value_t *result)
{
  PGresult *res;
  awk_value_t array;
  awk_value_t rowarg;
  int row;
  int nf;
  int found;
  int col;

  if (do_lint && (nargs > 3))
    lintwarn(ext_id, _("pg_getrowbyname: called with too many arguments"));

  if (!(res = find_handle(results, 0))) {
    set_ERRNO(_("pg_getrowbyname called with unknown result handle"));
    RET_NUM(-1);
  }

  if (!get_argument(1, AWK_NUMBER, &rowarg)) {
    set_ERRNO(_("pg_getrowbyname: 2nd argument must be a row number"));
    RET_NUM(-1);
  }
  row = rowarg.num_value;

  if ((row < 0) || (row >= PQntuples(res))) {
    set_ERRNO(_("pg_getrowbyname: 2nd argument row_number is out of range"));
    RET_NUM(-1);
  }

  if (!get_argument(2, AWK_ARRAY, &array)) {
    set_ERRNO(_("pg_getrowbyname 3rd argument must be an array"));
    RET_NUM(-1);
  }
  clear_array(array.array_cookie);

  found = 0;
  nf = PQnfields(res);
  for (col = 0; col < nf; col++) {
    if (!PQgetisnull(res, row, col)) {
      char *fname;
      char *val;
      awk_value_t idx, value;

      fname = PQfname(res, col);
      val = PQgetvalue(res, row, col);
      set_array_element(array.array_cookie,
      			make_string_malloc(fname, strlen(fname), &idx),
			make_string_malloc(val, strlen(val), &value));
      found++;
    }
  }
  RET_NUM(found);
}