• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PQconnectdb函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: main

int main(int argc, const char * const *argv) {

  char *args_string;
  char *member_id;
  char *image_type;
  const char *sql_member_image_params[2];

#ifndef PUBLIC_ACCESS
#ifdef PUBLIC_AVATAR_ACCESS
  int authorization_required = 0;
#endif
  char *cookies;
  regex_t session_ident_regex;
  ssize_t start, length;
  regmatch_t session_ident_regmatch[3];
  char *session_ident;
  const char *sql_session_params[1];
#endif

  PGconn *conn;
  PGresult *dbr;

  args_string = getenv("QUERY_STRING");
  if (!args_string) {
    fputs("Status: 403 Access Denied\n\n", stdout);
    return 0;
  }

  member_id   = strtok(args_string, "+");
  image_type  = strtok(NULL, "+");
  if (!member_id || !image_type) {
    fputs("Status: 403 Access Denied\n\n", stdout);
    return 0;
  }
  sql_member_image_params[0] = member_id;
  sql_member_image_params[1] = image_type;

#ifndef PUBLIC_ACCESS
#ifdef PUBLIC_AVATAR_ACCESS
  if (strcmp(image_type, "avatar")) {
    authorization_required = 1;
#endif
    cookies = getenv("HTTP_COOKIE");
    if (!args_string || !cookies) {
      fputs("Status: 403 Access Denied\n\n", stdout);
      return 0;
    }
    if (regcomp(&session_ident_regex, "(^|[; \t])liquid_feedback_session=([0-9A-Za-z]+)", REG_EXTENDED) != 0) {
      // shouldn't happen
      abort();
    }
    if (regexec(&session_ident_regex, cookies, 3, session_ident_regmatch, 0) != 0) {
      fputs("Status: 403 Access Denied\n\n", stdout);
      return 0;
    }
    start = session_ident_regmatch[2].rm_so;
    length = session_ident_regmatch[2].rm_eo - session_ident_regmatch[2].rm_so;
    session_ident = malloc(length + 1);
    if (!session_ident) abort();  // shouldn't happen
    strncpy(session_ident, cookies + start, length);
    session_ident[length] = 0;
    sql_session_params[0] = session_ident;
#ifdef PUBLIC_AVATAR_ACCESS
  }
#endif
#endif

  conn = PQconnectdb(GETPIC_CONNINFO);
  if (!conn) {
    fputs("Could not create PGconn structure.\n", stderr);
    return 1;
  }
  if (PQstatus(conn) != CONNECTION_OK) {
    fputs(PQerrorMessage(conn), stderr);
    PQfinish(conn);
    return 1;
  }

#ifndef PUBLIC_ACCESS
#ifdef PUBLIC_AVATAR_ACCESS
  if (authorization_required) {
#endif
    dbr = PQexecParams(conn,
      "SELECT NULL FROM session JOIN member ON member.id = session.member_id WHERE session.ident = $1 AND member.active",
      1, NULL, sql_session_params, NULL, NULL, 0
    );
    if (PQresultStatus(dbr) != PGRES_TUPLES_OK) {
      fputs(PQresultErrorMessage(dbr), stderr);
      PQfinish(conn);
      return 1;
    }
    if (PQntuples(dbr) != 1) {
      fputs("Status: 403 Access Denied\n\n", stdout);
      PQfinish(conn);
      return 0;
    }
#ifdef PUBLIC_AVATAR_ACCESS
  }
#endif
#endif
//.........这里部分代码省略.........
开发者ID:plattformbrandenburg,项目名称:liquid_feedback_frontend-fork,代码行数:101,代码来源:getpic.c


示例17: MakeDBConnection

/*
 * MakeDBConnection: This function creates a connection string based on
 * fields in the SegmentDatabase parameter and then connects to the database.
 * The PGconn* is returned.  Y=This must be checked by the calling
 * routine for errors etc.
 */
PGconn *
MakeDBConnection(const SegmentDatabase *pSegDB, bool bDispatch)
{
	char	   *pszOptions;
	char	   *pszHost;
	char	   *pszDBName;
	char	   *tmpDBName = NULL;
	char	   *pszUser;
	char	   *pszDBPswd;
	char	   *pszConnInfo;
	PGconn	   *pConn;


	if (bDispatch)
		pszOptions = NULL;
	else
		pszOptions = MakeString("options='-c gp_session_role=UTILITY'");

	if (pSegDB->pszHost == NULL || *pSegDB->pszHost == '\0')
		pszHost = strdup("host=''");
	else
		pszHost = MakeString("host=%s", pSegDB->pszHost);

	if (pSegDB->pszDBName != NULL && *pSegDB->pszDBName != '\0')
	{
		tmpDBName = escape_backslashes(pSegDB->pszDBName, true);
		pszDBName = MakeString("dbname='%s'", tmpDBName);
	}
	else
		pszDBName = NULL;

	if (pSegDB->pszDBUser != NULL && *pSegDB->pszDBUser != '\0')
		pszUser = MakeString("user=%s", pSegDB->pszDBUser);
	else
		pszUser = NULL;

	if (pSegDB->pszDBPswd != NULL && *pSegDB->pszDBPswd != '\0')
		pszDBPswd = MakeString("password='%s'", pSegDB->pszDBPswd);
	else
		pszDBPswd = NULL;

	pszConnInfo = MakeString("%s %s port=%u %s %s %s",
							 StringNotNull(pszOptions, ""),
							 pszHost,
							 pSegDB->port,
							 StringNotNull(pszDBName, ""),
							 //database,
							 StringNotNull(pszUser, ""),
							 StringNotNull(pszDBPswd, ""));

	pConn = PQconnectdb(pszConnInfo);

	if (pszOptions != NULL)
		free(pszOptions);
	if (pszHost != NULL)
		free(pszHost);
	if (tmpDBName != NULL)
		free(tmpDBName);
	if (pszDBName != NULL)
		free(pszDBName);
	if (pszUser != NULL)
		free(pszUser);
	if (pszDBPswd != NULL)
		free(pszDBPswd);
	if (pszConnInfo != NULL)
		free(pszConnInfo);

	return pConn;
}
开发者ID:PengJi,项目名称:gpdb-comments,代码行数:75,代码来源:cdb_dump_util.c


示例18: main


//.........这里部分代码省略.........
        fprintf(stderr, "Error: --drop only makes sense with --slim.\n");
        exit(EXIT_FAILURE);
    }

    if (unlogged && !create) {
        fprintf(stderr, "Warning: --unlogged only makes sense with --create; ignored.\n");
        unlogged = 0;
    }

    if (enable_hstore == HSTORE_NONE && !n_hstore_columns && hstore_match_only)
    {
        fprintf(stderr, "Warning: --hstore-match-only only makes sense with --hstore, --hstore-all, or --hstore-column; ignored.\n");
        hstore_match_only = 0;
    }

    if (enable_hstore_index && enable_hstore  == HSTORE_NONE && !n_hstore_columns) {
        fprintf(stderr, "Warning: --hstore-add-index only makes sense with hstore enabled.\n");
        enable_hstore_index = 0;
    }

    if (cache < 0) cache = 0;

    if (num_procs < 1) num_procs = 1;

    if (pass_prompt)
        password = simple_prompt("Password:", 100, 0);
    else {
        password = getenv("PGPASS");
    }

    

    conninfo = build_conninfo(db, username, password, host, port);
    sql_conn = PQconnectdb(conninfo);
    if (PQstatus(sql_conn) != CONNECTION_OK) {
        fprintf(stderr, "Error: Connection to database failed: %s\n", PQerrorMessage(sql_conn));
        exit(EXIT_FAILURE);
    }
    if (unlogged && PQserverVersion(sql_conn) < 90100) {
        fprintf(stderr, "Error: --unlogged works only with PostgreSQL 9.1 and above, but\n");
        fprintf(stderr, "you are using PostgreSQL %d.%d.%d.\n", PQserverVersion(sql_conn) / 10000, (PQserverVersion(sql_conn) / 100) % 100, PQserverVersion(sql_conn) % 100);
        exit(EXIT_FAILURE);
    }

    PQfinish(sql_conn);

    text_init();
    initList(&osmdata.tags);

    osmdata.count_node = osmdata.max_node = 0;
    osmdata.count_way  = osmdata.max_way  = 0;
    osmdata.count_rel  = osmdata.max_rel  = 0;

    LIBXML_TEST_VERSION

    project_init(projection);
    fprintf(stderr, "Using projection SRS %d (%s)\n", 
        project_getp 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PQdb函数代码示例发布时间:2022-05-30
下一篇:
C++ PQcmdTuples函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap