当前位置: 首页>>代码示例>>C++>>正文


C++ PQconnectdb函数代码示例

本文整理汇总了C++中PQconnectdb函数的典型用法代码示例。如果您正苦于以下问题:C++ PQconnectdb函数的具体用法?C++ PQconnectdb怎么用?C++ PQconnectdb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了PQconnectdb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: insert_logentry

void insert_logentry(ACE_CString pq, ACE_CString dig, ACE_CString step0, ACE_CString note, ACE_CString dest){
  /*
  ACE_DEBUG((LM_INFO,
	     "note = %s dest= %s\n", note.c_str(),dest.c_str()));
  */
  ACE_CString sql = "insert into logentry0(pq,dig,note,dest,valid,setup) values('" + pq +"','" +dig+"','";
  sql += note + "','";
  sql += dest + "', 1, now())" ;
  /*
  ACE_DEBUG((LM_INFO,
	     "(%P|%t):%l sql = %s\n", sql.c_str()));
*/
  PGconn* con;
  PGresult* res;
  con = PQconnectdb("host=45.33.3.188 port=5432 dbname=nv user=dec");
  if(PQstatus(con)!= CONNECTION_OK){
    ACE_DEBUG((LM_INFO,
	       "Connection to database failed:%s\n",
	       PQerrorMessage(con)));
    reclaim_conn(con);
  }
  PQexec(con, sql.c_str());
  reclaim_conn(con);
}
开发者ID:jungu,项目名称:brokenseal,代码行数:24,代码来源:logS.cpp

示例2: Exception

void DBConnection::connect(void)
{
	QString str_aux;

	/* If the connection string is not established indicates that the user
		is trying to connect without configuring connection parameters,
		thus an error is raised */
	if(connection_str=="")
		throw Exception(ERR_CONNECTION_NOT_CONFIGURED, __PRETTY_FUNCTION__, __FILE__, __LINE__);

	//Try to connect to the database
	connection=PQconnectdb(connection_str.toStdString().c_str());

	/* If the connection descriptor has not been allocated or if the connection state
		is CONNECTION_BAD it indicates that the connection was not successful */
	if(connection==NULL || PQstatus(connection)==CONNECTION_BAD)
	{
		//Raise the error generated by the DBMS
		str_aux=QString(Exception::getErrorMessage(ERR_CONNECTION_NOT_STABLISHED))
						.arg(PQerrorMessage(connection));
		throw Exception(str_aux, ERR_CONNECTION_NOT_STABLISHED,
										__PRETTY_FUNCTION__, __FILE__, __LINE__);
	}
}
开发者ID:Tbxhs,项目名称:pgmodeler,代码行数:24,代码来源:dbconnection.cpp

示例3: write_log

void CPokerTrackerThread::Connect(void) {
	 write_log(preferences.debug_pokertracker(), "[PokerTracker] Trying to open PostgreSQL DB...\n");
	if (!AllConnectionDataSpecified()) 	{
     write_log(preferences.debug_pokertracker(), "[PokerTracker] Can't connect to DB. Vital data missing\n");
		return;
	}
	_conn_str = CreateConnectionString(preferences.pt_ip_addr(), 
		preferences.pt_port(), preferences.pt_user(), preferences.pt_pass(), preferences.pt_dbname());
	_pgconn = PQconnectdb(_conn_str.GetString());

	if (PQstatus(_pgconn) == CONNECTION_OK)	{
		 write_log(preferences.debug_pokertracker(), "[PokerTracker] PostgreSQL DB opened successfully <%s/%s/%s>\n", 
			preferences.pt_ip_addr(), 
			preferences.pt_port(), 
			preferences.pt_dbname());

		_connected = true;
	}	else {
		 write_log(preferences.debug_pokertracker(), "[PokerTracker] ERROR opening PostgreSQL DB: %s\n\n", PQerrorMessage(_pgconn));
		PQfinish(_pgconn);
		_connected = false;
		_pgconn = NULL;
	}
}
开发者ID:alekseyf,项目名称:openholdembot-1,代码行数:24,代码来源:CPokerTrackerThread.cpp

示例4: main

int main(int argc, char **argv) {
  
  strcpy(baza, argv[1]);
  //należy uzupelnic dane
  sprintf(zapytanie, "host=localhost port=5432 dbname=%s user= password=", baza);
  conn = PQconnectdb(zapytanie); 
  
if (PQstatus(conn) == CONNECTION_OK) {
  printf("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
  printf("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv = \"Content-type\" content = \"text/html; charset=iso-8859-2\"/><title>zad2</title><style type=\"text/css\">table { border-color: DarkOrchid; border-style: solid; }</style></head><body bgcolor = 'aqua'>\n");
  
		for (i = 2; i < argc; ++i) {
			strcpy(tabela, argv[i]);
			sprintf(zapytanie, "SELECT * FROM %s", tabela);
			result = PQexec(conn, zapytanie);
			PQprint2(result);
		}
		
printf("</body></html>\n");
}
  
  PQfinish(conn);
  return EXIT_SUCCESS;
}
开发者ID:phass,项目名称:C_and_Cpp,代码行数:24,代码来源:psql2.c

示例5: main

int main()
{
  // próba po³±czenia
  PGconn *myconnection = PQconnectdb("");
  // sprawdzamy status po³±czenia
  if(PQstatus(myconnection) == CONNECTION_OK) {
    printf("connection made\n");
    // informacje o po³±czeniu
    printf("PGDBNAME   = %s\n",PQdb(myconnection));
    printf("PGUSER     = %s\n",PQuser(myconnection));
    printf("PGPASSWORD = %s\n",PQpass(myconnection));
    printf("PGHOST     = %s\n",PQhost(myconnection));
    printf("PGPORT     = %s\n",PQport(myconnection));
    printf("OPTIONS    = %s\n",PQoptions(myconnection));
  }
  else
    printf("connection failed: %s\n", PQerrorMessage(myconnection));
  // w razie utraty po³±czenia wywo³anie 
  // PQreset(myconnection);
  // zamyka op³±czenie i nawi±zuje je raz jeszcze  
  // z dotychczasowymi parametrami
  PQfinish(myconnection);
  return EXIT_SUCCESS;
}
开发者ID:swistak,项目名称:skarbnik,代码行数:24,代码来源:connect.c

示例6: pg_internal_conn

/* perform an internal connection to the database in separate process and execute sql
 * statement */
bRC pg_internal_conn ( bpContext *ctx, const char * sql ){

   PGconn * db;
   ConnStatusType status;
   PGresult * result;
   int pid = 0;
   struct stat st;
   uid_t pguid;
   int err;
   char connstring[CONNSTRLEN];
   pgsqlpinst * pinst;
   bRC exitstatus = bRC_OK;

   /* check input data */
   ASSERT_ctx_p;
   pinst = (pgsqlpinst *)ctx->pContext;

   /* dynamic production database owner verification, we use it do connect to production
    * database. Required PGDATA from config file */
   ASSERT_p ( pinst->paramlist );
   err = stat ( search_key ( pinst->paramlist, "PGDATA" ) , &st );
   if ( err ){
      /* error, invalid PGDATA in config file */
//FIXME      printf ( PLUGIN_INFO "invalid 'PGDATA' variable in config file.\n" );
      return bRC_Error;
   }
   /* we will fork to the owner of PGDATA database cluster */
   pguid = st.st_uid;

   /* switch pg xlog in different process, so make a fork */
   pid = fork ();
   if ( pid == 0 ){
//      printf ( PLUGIN_INFO "forked process\n" );
      /* sleep used for debuging forked process in gdb */
      // sleep ( 60 );

      /* we are in forked process, do a real job */
      /* switch to pgcluster owner (postgres) */
      err = seteuid ( pguid );
      if ( err ){
         /* error switching uid, report a problem */
         /* TODO: add an errorlog display */
//FIXME         printf ( PLUGIN_INFO "seteuid to uid=%i failed!\n", pguid );
         exit (bRC_Error);
      }
      /* host is a socket directory, port is a socket 'port', we perform an 'internal'
       * connection through a postgresql socket, which is required by plugin */
      snprintf ( connstring, CONNSTRLEN, "host=%s port=%s",
            search_key ( pinst->paramlist, "PGHOST" ),
            search_key ( pinst->paramlist, "PGPORT" ) );

      db = PQconnectdb ( connstring );
      status = PQstatus ( db );
      if ( status == CONNECTION_BAD ){
         /* TODO: add an errorlog display */
//FIXME         printf ( PLUGIN_INFO "conndb failed!\n");
         exit (bRC_Error);
      }

      /* we have a successful production database connection, so execute sql */
      result = PQexec ( db, sql );
      if ( PQresultStatus ( result ) != PGRES_TUPLES_OK ){
         /* TODO: add an errorlog display */
//FIXME         printf ( PLUGIN_INFO "pg_internal_conn failed! (%s)\n", sql);
         exit (bRC_Error);
      }

      /* finish database connection */
      PQfinish ( db );

      /* finish forked process */
      exit (bRC_OK);
   } else {
      /* we are waiting for background process to finish */
      waitpid ( pid, (int*)&exitstatus, 0 );
   }

   /* XXX: we should check for forked process exit status */

   return exitstatus;
}
开发者ID:bareos,项目名称:contrib-pgsql-plugin,代码行数:83,代码来源:pgsqllib.c

示例7: msPOSTGRESQLJoinConnect

int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join) {
    char *maskeddata, *temp, *sql, *column;
    char *conn_decrypted;
    int i, count, test;
    PGresult *query_result;
    msPOSTGRESQLJoinInfo *joininfo;

    if(join->joininfo) 
        return MS_SUCCESS;

    joininfo = (msPOSTGRESQLJoinInfo *)malloc(sizeof(msPOSTGRESQLJoinInfo));
    if(!joininfo) {
        msSetError(MS_MEMERR, "Error allocating join info struct.", 
                "msPOSTGRESQLJoinConnect()");
        return MS_FAILURE;
    }
    joininfo->conn = NULL;
    joininfo->row_num = 0;
    joininfo->query_result = NULL;
    joininfo->from_index = 0;
    joininfo->to_column = join->to;
    joininfo->from_value = NULL;
    joininfo->layer_debug = layer->debug;
    join->joininfo = joininfo;

    /* 
     * We need three things at a minimum, the connection string, a table
     * name, and a column to join on.
     */
    if(!join->connection) {
        msSetError(MS_QUERYERR, "No connection information provided.", 
                "MSPOSTGRESQLJoinConnect()");
        return MS_FAILURE;
    }
    if(!join->table) {
        msSetError(MS_QUERYERR, "No join table name found.", 
                "msPOSTGRESQLJoinConnect()");
        return MS_FAILURE;
    }
    if(!joininfo->to_column) {
        msSetError(MS_QUERYERR, "No join to column name found.",
                "msPOSTGRESQLJoinConnect()");
        return MS_FAILURE;
    }

    /* Establish database connection */
    conn_decrypted = msDecryptStringTokens(layer->map, join->connection);
    if (conn_decrypted != NULL) {
      joininfo->conn = PQconnectdb(conn_decrypted);
      free(conn_decrypted);
    }
    if(!joininfo->conn || PQstatus(joininfo->conn) == CONNECTION_BAD) {
        maskeddata = (char *)malloc(strlen(layer->connection) + 1);
        strcpy(maskeddata, join->connection);
        temp = strstr(maskeddata, "password=");
        if(!temp) {
            temp = (char *)(temp + 9);
            count = (int)(strstr(temp, " ") - temp);
            for(i = 0; i < count; i++) {
                strlcpy(temp, "*", (int)1);
                temp++;
            }
        }
        msSetError(MS_QUERYERR, 
                "Unable to connect to PostgreSQL using the string %s.\n  Error reported: %s\n", 
                "msPOSTGRESQLJoinConnect()", 
                maskeddata, PQerrorMessage(joininfo->conn));
        free(maskeddata);
        if(!joininfo->conn) {
            free(joininfo->conn);
        }
        free(joininfo);
        join->joininfo = NULL;
        return MS_FAILURE;
    }

    /* Determine the number and names of columns in the join table. */
    sql = (char *)malloc(36 + strlen(join->table) + 1);
    sprintf(sql, "SELECT * FROM %s WHERE false LIMIT 0", join->table);
    
    if(joininfo->layer_debug) {
        msDebug("msPOSTGRESQLJoinConnect(): executing %s.\n", sql);
    }

    query_result = PQexec(joininfo->conn, sql);
    if(!query_result || PQresultStatus(query_result) != PGRES_TUPLES_OK) {
        msSetError(MS_QUERYERR, "Error determining join items: %s.", 
                "msPOSTGRESQLJoinConnect()", PQerrorMessage(joininfo->conn));
        if(query_result) {
            PQclear(query_result);
            query_result = NULL;
        }
        free(sql);
        return MS_FAILURE;
    }
    free(sql);
    join->numitems = PQnfields(query_result);
    join->items = malloc(sizeof(char *) * (join->numitems));

    /* We want the join-to column to be first in the list. */
//.........这里部分代码省略.........
开发者ID:msilex,项目名称:mapserver,代码行数:101,代码来源:mappostgresql.c

示例8: cmd_open


//.........这里部分代码省略.........
      if (reason_len == 0) {
        reason = "(unknown)";
        reason_len = strlen(reason);
      }

      /* The error message returned by Postgres is usually appended with
       * a newline.  Let's prettify it by removing the newline.  Note
       * that yes, we are overwriting the pointer given to us by Postgres,
       * but it's OK.  The Postgres docs say that we're not supposed to
       * free the memory associated with the returned string anyway.
       */
      reason = pstrdup(session.pool, reason);

      if (reason[reason_len-1] == '\n') {
        reason[reason_len-1] = '\0';
        reason_len--;
      }

      sql_log(DEBUG_INFO, "lost connection to database: %s", reason);

      entry->connections = 0;
      if (entry->timer) {
        pr_timer_remove(entry->timer, &sql_postgres_module);
        entry->timer = 0;
      }

      sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
      return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION,
        "lost connection to database");
    }
  }

  /* make sure we have a new conn struct */
  conn->postgres = PQconnectdb(conn->connectstring);
  
  if (PQstatus(conn->postgres) == CONNECTION_BAD) {
    /* if it didn't work, return an error */
    sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
    return _build_error( cmd, conn );
  }

#if defined(PG_VERSION_STR)
  sql_log(DEBUG_FUNC, "Postgres client: %s", PG_VERSION_STR);
#endif

  server_version = PQparameterStatus(conn->postgres, "server_version");
  if (server_version != NULL) {
    sql_log(DEBUG_FUNC, "Postgres server version: %s", server_version);
  }

#ifdef PR_USE_NLS
  if (pr_encode_get_encoding() != NULL) {
    const char *encoding;

    encoding = get_postgres_encoding(pr_encode_get_encoding());

    /* Configure the connection for the current local character set. */
    if (PQsetClientEncoding(conn->postgres, encoding) < 0) {
      /* if it didn't work, return an error */
      sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open");
      return _build_error(cmd, conn);
    }

    sql_log(DEBUG_FUNC, "Postgres connection character set now '%s' "
      "(from '%s')", pg_encoding_to_char(PQclientEncoding(conn->postgres)),
      pr_encode_get_encoding());
开发者ID:Distrotech,项目名称:proftpd,代码行数:67,代码来源:mod_sql_postgres.c

示例9: libpqrcv_connect

/*
 * Establish the connection to the primary server for XLOG streaming
 */
static bool
libpqrcv_connect(char *conninfo, XLogRecPtr startpoint)
{
	char		conninfo_repl[MAXCONNINFO + 37];
	char	   *primary_sysid;
	char		standby_sysid[32];
	TimeLineID	primary_tli;
	TimeLineID	standby_tli;
	PGresult   *res;
	char		cmd[64];

	/*
	 * Connect using deliberately undocumented parameter: replication. The
	 * database name is ignored by the server in replication mode, but specify
	 * "replication" for .pgpass lookup.
	 */
	snprintf(conninfo_repl, sizeof(conninfo_repl),
			 "%s dbname=replication replication=true",
			 conninfo);

	streamConn = PQconnectdb(conninfo_repl);
	if (PQstatus(streamConn) != CONNECTION_OK)
		ereport(ERROR,
				(errmsg("could not connect to the primary server: %s",
						PQerrorMessage(streamConn))));

	/*
	 * Get the system identifier and timeline ID as a DataRow message from the
	 * primary server.
	 */
	res = libpqrcv_PQexec("IDENTIFY_SYSTEM");
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		PQclear(res);
		ereport(ERROR,
				(errmsg("could not receive database system identifier and timeline ID from "
						"the primary server: %s",
						PQerrorMessage(streamConn))));
	}
	if (PQnfields(res) != 2 || PQntuples(res) != 1)
	{
		int			ntuples = PQntuples(res);
		int			nfields = PQnfields(res);

		PQclear(res);
		ereport(ERROR,
				(errmsg("invalid response from primary server"),
				 errdetail("Expected 1 tuple with 2 fields, got %d tuples with %d fields.",
						   ntuples, nfields)));
	}
	primary_sysid = PQgetvalue(res, 0, 0);
	primary_tli = pg_atoi(PQgetvalue(res, 0, 1), 4, 0);

	/*
	 * Confirm that the system identifier of the primary is the same as ours.
	 */
	snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
			 GetSystemIdentifier());
	if (strcmp(primary_sysid, standby_sysid) != 0)
	{
		PQclear(res);
		ereport(ERROR,
				(errmsg("database system identifier differs between the primary and standby"),
				 errdetail("The primary's identifier is %s, the standby's identifier is %s.",
						   primary_sysid, standby_sysid)));
	}

	/*
	 * Confirm that the current timeline of the primary is the same as the
	 * recovery target timeline.
	 */
	standby_tli = GetRecoveryTargetTLI();
	PQclear(res);
	if (primary_tli != standby_tli)
		ereport(ERROR,
				(errmsg("timeline %u of the primary does not match recovery target timeline %u",
						primary_tli, standby_tli)));
	ThisTimeLineID = primary_tli;

	/* Start streaming from the point requested by startup process */
	snprintf(cmd, sizeof(cmd), "START_REPLICATION %X/%X",
			 startpoint.xlogid, startpoint.xrecoff);
	res = libpqrcv_PQexec(cmd);
	if (PQresultStatus(res) != PGRES_COPY_BOTH)
	{
		PQclear(res);
		ereport(ERROR,
				(errmsg("could not start WAL streaming: %s",
						PQerrorMessage(streamConn))));
	}
	PQclear(res);

	justconnected = true;
	ereport(LOG,
		(errmsg("streaming replication successfully connected to primary")));

	return true;
//.........这里部分代码省略.........
开发者ID:gurjeet,项目名称:postgres,代码行数:101,代码来源:libpqwalreceiver.c

示例10: PQconnectdb

// this constructor creates empty network
// this is base for network mapping
IONet::IONet() {

	// create map to keep all pages
	this->ioPages	=	new std::map<int, IONetPage> ();

	// create connection to the server
	std::string conncetString = CS_SUP_HOST + " " +
								CS_SUP_USER + " " +
								CS_SUP_PWD + " " +
								CS_SUP_DBNAME ;
	this->databaseConnection = PQconnectdb("host=localhost user=postgres password=postgres dbname=RoverConfiguration");

	//check connection status
	switch (PQstatus(this->databaseConnection)) {
	case CONNECTION_OK:
		std::cout << "Connection is OK" << std::endl ;
		break ;
	case CONNECTION_BAD:
		std::cout << "Connection is bad." << std::endl ;
		break ;
	default:
		std::cout << "status is other" << std::endl ;
		break ;
	}

	// now we get list of variables
	bool resultOK = false ;
	PGresult *queryResult = PQexec( this->databaseConnection, "select * from public.\"IONetwork\"" ) ;
	if (queryResult != NULL) {
		switch (PQresultStatus(queryResult)){
		case PGRES_TUPLES_OK:
			std::cout << "result OK" << std::endl ;
			resultOK = true ;
			break ;
		case PGRES_COMMAND_OK:
			std::cout << "command OK" << std::endl ;
			resultOK = true ;
			break ;
		case PGRES_EMPTY_QUERY:
			std::cout << "empty query" << std::endl ;
			break ;
		case PGRES_BAD_RESPONSE:
			std::cout << "bad response" << std::endl ;
			break ;
		case PGRES_FATAL_ERROR:
			std::cout << "fatal error: " << PQerrorMessage(this->databaseConnection) << std::endl ;
			break ;
		case PGRES_NONFATAL_ERROR:
			std::cout << "non-fatal error" << std::endl ;
			break ;
		default:
			std::cout << "result not OK" << std::endl ;
			break ;
		}
	} else {
		std::cout << "result is NULL" << std::endl ;
	}

	// of there were rows returned
	if (resultOK) {
		std::cout << "returned " << PQntuples(queryResult) << " rows x "
				  << PQnfields(queryResult) << " columns" << std::endl ;
		std::cout << "-----------------" << std::endl ;

		int returnedRows = PQntuples(queryResult) ;
		int returnedCols = PQnfields(queryResult) ;

		// create temporary map
		std::map<std::string, IONetVar> *tempMap = new std::map<std::string, IONetVar>() ;

		for (int i=0; i<returnedRows; i++){
			int *variable = new int();
			std::string varName = PQgetvalue(queryResult, i, 0) ;

			IONetVar *netVarA = new IONetVar((char*)variable, integer, varName) ;
			tempMap->insert(std::pair<std::string, IONetVar>(varName, *netVarA)) ;
			delete variable ;
			delete netVarA ;
		}

		// add new page
		this->addPage(1, *tempMap);
		delete tempMap ;
	}

}
开发者ID:dohtem81,项目名称:IONet,代码行数:88,代码来源:IONet.cpp

示例11: config_connect

static int
config_connect(struct config *conf)
{
	static const struct {
		const char	*name;
		int		 cols;
	} qspec[SQL_MAX] = {
		{ "query_alias",	1 },
		{ "query_domain",	1 },
		{ "query_credentials",	2 },
		{ "query_netaddr",	1 },
		{ "query_userinfo",	3 },
		{ "query_source",	1 },
		{ "query_mailaddr",	1 },
		{ "query_addrname",	1 },
	};
	size_t	 i;
	char	*conninfo, *q;

	log_debug("debug: table-postgres: (re)connecting");

	/* Disconnect first, if needed */
	config_reset(conf);

	conninfo = dict_get(&conf->conf, "conninfo");
	if (conninfo == NULL) {
		log_warnx("warn: table-postgres: missing \"conninfo\" configuration directive");
		goto end;
	}

	conf->db = PQconnectdb(conninfo);
	if (conf->db == NULL) {
		log_warnx("warn: table-postgres: PQconnectdb return NULL");
		goto end;
	}
	if (PQstatus(conf->db) != CONNECTION_OK) {
		log_warnx("warn: table-postgres: PQconnectdb: %s",
		    PQerrorMessage(conf->db));
		goto end;
	}

	for (i = 0; i < SQL_MAX; i++) {
		q = dict_get(&conf->conf, qspec[i].name);
		if (q && (conf->statements[i] = table_postgres_prepare_stmt(
		    conf->db, q, 1, qspec[i].cols)) == NULL)
			goto end;
	}

	q = dict_get(&conf->conf, "fetch_source");
	if (q && (conf->stmt_fetch_source = table_postgres_prepare_stmt(conf->db,
	    q, 0, 1)) == NULL)
		goto end;

	log_debug("debug: table-postgres: connected");

	return (1);

    end:
	config_reset(conf);
	return (0);
}
开发者ID:gretel,项目名称:OpenSMTPD,代码行数:61,代码来源:table_postgres.c

示例12: main

int
main(int argc, char **argv)
{
	PGconn	   *conn;
	PQExpBufferData sql;
	PGresult   *res;
	PGresult   *pkrel_res;
	PGresult   *fkrel_res;
	char	   *fk_relname;
	char	   *fk_nspname;
	char	   *fk_attname;
	char	   *pk_relname;
	char	   *pk_nspname;
	int			fk,
				pk;				/* loop counters */

	if (argc != 2)
	{
		fprintf(stderr, "Usage:  %s database\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	initPQExpBuffer(&sql);

	appendPQExpBuffer(&sql, "dbname=%s", argv[1]);

	conn = PQconnectdb(sql.data);
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		fprintf(stderr, "connection error:  %s\n", PQerrorMessage(conn));
		exit(EXIT_FAILURE);
	}

	/* Get a list of relations that have OIDs */

	printfPQExpBuffer(&sql, "%s",
					  "SET search_path = public;"
					  "SELECT c.relname, (SELECT nspname FROM "
					  "pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname "
					  "FROM pg_catalog.pg_class c "
					  "WHERE c.relkind = " CppAsString2(RELKIND_RELATION)
					  " AND c.relhasoids "
					  "ORDER BY nspname, c.relname"
		);

	res = PQexec(conn, sql.data);
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "sql error:  %s\n", PQerrorMessage(conn));
		exit(EXIT_FAILURE);
	}
	pkrel_res = res;

	/* Get a list of columns of OID type (or any OID-alias type) */

	printfPQExpBuffer(&sql, "%s",
					  "SELECT c.relname, "
					  "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, "
					  "a.attname "
					  "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a "
					  "WHERE a.attnum > 0"
					  " AND c.relkind = " CppAsString2(RELKIND_RELATION)
					  " AND a.attrelid = c.oid"
					  " AND a.atttypid IN ('pg_catalog.oid'::regtype, "
					  " 'pg_catalog.regclass'::regtype, "
					  " 'pg_catalog.regoper'::regtype, "
					  " 'pg_catalog.regoperator'::regtype, "
					  " 'pg_catalog.regproc'::regtype, "
					  " 'pg_catalog.regprocedure'::regtype, "
					  " 'pg_catalog.regtype'::regtype, "
					  " 'pg_catalog.regconfig'::regtype, "
					  " 'pg_catalog.regdictionary'::regtype) "
					  "ORDER BY nspname, c.relname, a.attnum"
		);

	res = PQexec(conn, sql.data);
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "sql error:  %s\n", PQerrorMessage(conn));
		exit(EXIT_FAILURE);
	}
	fkrel_res = res;

	/*
	 * For each column and each relation-having-OIDs, look to see if the
	 * column contains any values matching entries in the relation.
	 */

	for (fk = 0; fk < PQntuples(fkrel_res); fk++)
	{
		fk_relname = PQgetvalue(fkrel_res, fk, 0);
		fk_nspname = PQgetvalue(fkrel_res, fk, 1);
		fk_attname = PQgetvalue(fkrel_res, fk, 2);

		for (pk = 0; pk < PQntuples(pkrel_res); pk++)
		{
			pk_relname = PQgetvalue(pkrel_res, pk, 0);
			pk_nspname = PQgetvalue(pkrel_res, pk, 1);

			printfPQExpBuffer(&sql,
//.........这里部分代码省略.........
开发者ID:AmiGanguli,项目名称:postgres,代码行数:101,代码来源:findoidjoins.c

示例13: main

main()
{
	char       *pghost,
	*pgport,
	*pgoptions,
	*pgtty;
	char       *dbName;
	int         nFields;
	int         row,
	field;
	PGconn     *conn;
	PGresult   *res;
	int	junk;
	char	*field_name;
	int	field_type;
	int	WKB_OID;
	char		conn_string[255];

	bool		*bool_val;
	int		*int_val;
	float		*float_val;
	double	*double_val;
	char		*char_val;
	char		*wkb_val;
	char		*table_name = "wkbreader_test";
	char		query_str[1000];

	/* make a connection to the database */
	conn = PQconnectdb("");

	/*
	* check to see that the backend connection was successfully made
	*/
	if (PQstatus(conn) == CONNECTION_BAD)
	{
		fprintf(stderr, "%s", PQerrorMessage(conn));
		exit_nicely(conn);
	}

	//what is the geometry type's OID #?
	WKB_OID = find_WKB_typeid(conn);


	/* start a transaction block */
	res = PQexec(conn, "BEGIN");
	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "%s", PQerrorMessage(conn));
		PQclear(res);
		exit_nicely(conn);
	}

	/*
	 * should PQclear PGresult whenever it is no longer needed to avoid
	 * memory leaks
	 */
	PQclear(res);

	/*
	 * fetch rows from the pg_database, the system catalog of
	 * databases
	 */
	sprintf(query_str, "DECLARE mycursor BINARY CURSOR FOR select text(num), asbinary(the_geom,'ndr') as wkb from %s", table_name);

	printf(query_str);
	printf("\n");

	res = PQexec(conn, query_str);

	if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, "DECLARE CURSOR command failed\n");
		fprintf(stderr, "%s", PQerrorMessage(conn));
		PQclear(res);
		exit_nicely(conn);
	}
	PQclear(res);

	res = PQexec(conn, "FETCH ALL in mycursor");
	if (!res || PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, "FETCH ALL command didn't return tuples properly\n");
		fprintf(stderr, "%s", PQerrorMessage(conn));
		PQclear(res);
		exit_nicely(conn);
	}

	for (row=0; row< PQntuples(res); row++)
	{
		printf("------------------------------row %i --------------------------\n",row);
		//not so efficient, but...
		for (field =0 ; field< PQnfields(res); field++)
		{
			field_type =PQftype(res,field);
			field_name = PQfname(res, field);

			//we just handle a few of the popular type since this is just an example

			if (field_type ==16)// bool
			{
//.........这里部分代码省略.........
开发者ID:JeremyGrosser,项目名称:postgis,代码行数:101,代码来源:readwkb.c

示例14: map_collect_data_osm_db

int
map_collect_data_osm_db(char *dbstr, struct maptool_osm *osm)
{
	PGconn *conn;
	PGresult *res,*node,*way,*tag;
	int count,tagged,i,j,k;
	long min, max, id, tag_id, node_id;
	char query[256];
	
	sig_alrm(0);
	conn=PQconnectdb(dbstr);
	if (! conn) {
		fprintf(stderr,"Failed to connect to database with '%s'\n",dbstr);
		exit(1);
	}
	res=PQexec(conn, "begin");
	if (! res) {
		fprintf(stderr, "Cannot begin transaction: %s\n", PQerrorMessage(conn));
		PQclear(res);
		exit(1);
	}
	res=PQexec(conn, "set transaction isolation level serializable");
	if (! res) {
		fprintf(stderr, "Cannot set isolation level: %s\n", PQerrorMessage(conn));
		PQclear(res);
		exit(1);
	}
	res=PQexec(conn, "declare node cursor for select id,x(coordinate),y(coordinate) from node order by id");
	if (! res) {
		fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
		PQclear(res);
		exit(1);
	}
	res=PQexec(conn, "declare way cursor for select id from way order by id");
	if (! res) {
		fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
		PQclear(res);
		exit(1);
	}
	res=PQexec(conn, "declare relation cursor for select id from relation order by id");
	if (! res) {
		fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
		PQclear(res);
		exit(1);
	}
	for (;;) {
		node=PQexec(conn, "fetch 100000 from node");
		if (! node) {
			fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn));
			PQclear(node);
			exit(1);
		}
		count=PQntuples(node);
		if (! count)
			break;
		min=atol(PQgetvalue(node, 0, 0));
		max=atol(PQgetvalue(node, count-1, 0));
		sprintf(query,"select node_id,name,value from node_tag where node_id >= %ld and node_id <= %ld order by node_id", min, max);
		tag=PQexec(conn, query);
		if (! tag) {
			fprintf(stderr, "Cannot query node_tag: %s\n", PQerrorMessage(conn));
			exit(1);
		}
		j=0;
		for (i = 0 ; i < count ; i++) {
			id=atol(PQgetvalue(node, i, 0));
			osm_add_node(id, atof(PQgetvalue(node, i, 1)), atof(PQgetvalue(node, i, 2)));
			tagged=0;
			processed_nodes++;
			while (j < PQntuples(tag)) {
				tag_id=atol(PQgetvalue(tag, j, 0));
				if (tag_id == id) {
					osm_add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2));
					tagged=1;
					j++;
				}
				if (tag_id < id)
					j++;
				if (tag_id > id)
					break;
			}
			osm_end_node(osm);
		}
		PQclear(tag);
		PQclear(node);
	}
	for (;;) {
		way=PQexec(conn, "fetch 100000 from way");
		if (! way) {
			fprintf(stderr, "Cannot setup cursor for ways: %s\n", PQerrorMessage(conn));
			PQclear(node);
			exit(1);
		}
		count=PQntuples(way);
		if (! count)
			break;
		min=atol(PQgetvalue(way, 0, 0));
		max=atol(PQgetvalue(way, count-1, 0));
		sprintf(query,"select way_id,node_id from way_node where way_id >= %ld and way_id <= %ld order by way_id,sequence_id", min, max);
		node=PQexec(conn, query);
//.........这里部分代码省略.........
开发者ID:Jalakas,项目名称:navit,代码行数:101,代码来源:osm_psql.c

示例15: main


//.........这里部分代码省略.........
	/* Verify that all step names are unique */
	for (i = 1; i < testspec->nallsteps; i++)
	{
		if (strcmp(testspec->allsteps[i - 1]->name,
				   testspec->allsteps[i]->name) == 0)
		{
			fprintf(stderr, "duplicate step name: %s\n",
					testspec->allsteps[i]->name);
			exit_nicely();
		}
	}

	/*
	 * In dry-run mode, just print the permutations that would be run, and
	 * exit.
	 */
	if (dry_run)
	{
		run_testspec(testspec);
		return 0;
	}

	printf("Parsed test spec with %d sessions\n", testspec->nsessions);

	/*
	 * Establish connections to the database, one for each session and an
	 * extra for lock wait detection and global work.
	 */
	nconns = 1 + testspec->nsessions;
	conns = calloc(nconns, sizeof(PGconn *));
	backend_pids = calloc(nconns, sizeof(*backend_pids));
	for (i = 0; i < nconns; i++)
	{
		conns[i] = PQconnectdb(conninfo);
		if (PQstatus(conns[i]) != CONNECTION_OK)
		{
			fprintf(stderr, "Connection %d to database failed: %s",
					i, PQerrorMessage(conns[i]));
			exit_nicely();
		}

		/*
		 * Suppress NOTIFY messages, which otherwise pop into results at odd
		 * places.
		 */
		res = PQexec(conns[i], "SET client_min_messages = warning;");
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "message level setup failed: %s", PQerrorMessage(conns[i]));
			exit_nicely();
		}
		PQclear(res);

		/* Get the backend pid for lock wait checking. */
		res = PQexec(conns[i], "SELECT pg_backend_pid()");
		if (PQresultStatus(res) == PGRES_TUPLES_OK)
		{
			if (PQntuples(res) == 1 && PQnfields(res) == 1)
				backend_pids[i] = strdup(PQgetvalue(res, 0, 0));
			else
			{
				fprintf(stderr, "backend pid query returned %d rows and %d columns, expected 1 row and 1 column",
						PQntuples(res), PQnfields(res));
				exit_nicely();
			}
		}
开发者ID:BenjaminYu,项目名称:postgres,代码行数:67,代码来源:isolationtester.c


注:本文中的PQconnectdb函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。