本文整理汇总了C++中PQexec函数的典型用法代码示例。如果您正苦于以下问题:C++ PQexec函数的具体用法?C++ PQexec怎么用?C++ PQexec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PQexec函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: SendQuery
/*
* SendQuery: send the query string to the backend
* (and print out results)
*
* Note: This is the "front door" way to send a query. That is, use it to
* send queries actually entered by the user. These queries will be subject to
* single step mode.
* To send "back door" queries (generated by slash commands, etc.) in a
* controlled way, use PSQLexec().
*
* Returns true if the query executed successfully, false otherwise.
*/
bool
SendQuery(const char *query)
{
PGresult *results;
TimevalStruct before,
after;
bool OK;
if (!pset.db)
{
psql_error("You are currently not connected to a database.\n");
return false;
}
if (GetVariableBool(pset.vars, "SINGLESTEP"))
{
char buf[3];
printf(gettext("***(Single step mode: verify command)*******************************************\n"
"%s\n"
"***(press return to proceed or enter x and return to cancel)********************\n"),
query);
fflush(stdout);
if (fgets(buf, sizeof(buf), stdin) != NULL)
if (buf[0] == 'x')
return false;
}
else if (VariableEquals(pset.vars, "ECHO", "queries"))
{
puts(query);
fflush(stdout);
}
SetCancelConn();
if (PQtransactionStatus(pset.db) == PQTRANS_IDLE &&
!GetVariableBool(pset.vars, "AUTOCOMMIT") &&
!is_transact_command(query))
{
results = PQexec(pset.db, "BEGIN");
if (PQresultStatus(results) != PGRES_COMMAND_OK)
{
psql_error("%s", PQerrorMessage(pset.db));
PQclear(results);
ResetCancelConn();
return false;
}
PQclear(results);
}
if (pset.timing)
GETTIMEOFDAY(&before);
results = PQexec(pset.db, query);
/* these operations are included in the timing result: */
OK = (AcceptResult(results) && ProcessCopyResult(results));
if (pset.timing)
GETTIMEOFDAY(&after);
/* but printing results isn't: */
if (OK)
OK = PrintQueryResults(results);
PQclear(results);
/* Possible microtiming output */
if (OK && pset.timing)
printf(gettext("Time: %.3f ms\n"), DIFF_MSEC(&after, &before));
/* check for events that may occur during query execution */
if (pset.encoding != PQclientEncoding(pset.db) &&
PQclientEncoding(pset.db) >= 0)
{
/* track effects of SET CLIENT_ENCODING */
pset.encoding = PQclientEncoding(pset.db);
pset.popt.topt.encoding = pset.encoding;
SetVariable(pset.vars, "ENCODING",
pg_encoding_to_char(pset.encoding));
}
PrintNotifications();
return OK;
}
示例2: msPOSTGRESQLJoinNext
int msPOSTGRESQLJoinNext(joinObj *join)
{
msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
int i, length, row_count;
char *sql, *columns;
/* We need a connection, and a join value. */
if(!joininfo || !joininfo->conn) {
msSetError(MS_JOINERR, "Join has not been connected.\n",
"msPOSTGRESQLJoinNext()");
return MS_FAILURE;
}
if(!joininfo->from_value) {
msSetError(MS_JOINERR, "Join has not been prepared.\n",
"msPOSTGRESQLJoinNext()");
return MS_FAILURE;
}
/* Free the previous results. */
if(join->values) {
msFreeCharArray(join->values, join->numitems);
join->values = NULL;
}
/* We only need to execute the query if no results exist. */
if(!joininfo->query_result) {
/* Write the list of column names. */
length = 0;
for(i = 0; i < join->numitems; i++) {
length += 8 + strlen(join->items[i]) + 2;
}
columns = (char *)malloc(length);
if(!columns) {
msSetError(MS_MEMERR, "Failure to malloc.\n",
"msPOSTGRESQLJoinNext()");
return MS_FAILURE;
}
strcpy(columns, "");
for(i = 0; i < join->numitems; i++) {
strcat(columns, "\"");
strcat(columns, join->items[i]);
strcat(columns, "\"::text");
if(i != join->numitems - 1) {
strcat(columns, ", ");
}
}
/* Create the query string. */
sql = (char *)malloc(26 + strlen(columns) + strlen(join->table) +
strlen(join->to) + strlen(joininfo->from_value));
if(!sql) {
msSetError(MS_MEMERR, "Failure to malloc.\n",
"msPOSTGRESQLJoinNext()");
return MS_FAILURE;
}
sprintf(sql, "SELECT %s FROM %s WHERE %s = '%s'", columns, join->table, join->to, joininfo->from_value);
if(joininfo->layer_debug) {
msDebug("msPOSTGRESQLJoinNext(): executing %s.\n", sql);
}
free(columns);
joininfo->query_result = PQexec(joininfo->conn, sql);
if(!joininfo->query_result ||
PQresultStatus(joininfo->query_result) != PGRES_TUPLES_OK) {
msSetError(MS_QUERYERR, "Error executing queri %s: %s\n",
"msPOSTGRESQLJoinNext()", sql,
PQerrorMessage(joininfo->conn));
if(joininfo->query_result) {
PQclear(joininfo->query_result);
joininfo->query_result = NULL;
}
free(sql);
return MS_FAILURE;
}
free(sql);
}
row_count = PQntuples(joininfo->query_result);
/* see if we're done processing this set */
if(joininfo->row_num >= row_count) {
return(MS_DONE);
}
if(joininfo->layer_debug) {
msDebug("msPOSTGRESQLJoinNext(): fetching row %ld.\n",
joininfo->row_num);
}
/* Copy the resulting values into the joinObj. */
join->values = (char **)malloc(sizeof(char *) * join->numitems);
for(i = 0; i < join->numitems; i++) {
join->values[i] = msStrdup(PQgetvalue(
joininfo->query_result, joininfo->row_num, i));
}
joininfo->row_num++;
//.........这里部分代码省略.........
示例3: main
int main(int argc, char * argv[])
{
PGconn *conn;
PGresult *res;
char * conninfo = calloc (MAX_LEN, sizeof (char));
char * query = calloc (MAX_LEN, sizeof (char));
char * nama = calloc (MAX_LEN, sizeof (char));
char * alamat = calloc (MAX_LEN, sizeof (char));
char * temp = calloc (MAX_LEN, sizeof (char));
int field_count;
int rec_count;
int c,menu;
int i,j;
strcpy (conninfo, "dbname=test user=nop");
conn = PQconnectdb (conninfo);
if (PQstatus (conn) != CONNECTION_OK)
{
fprintf (stderr, "Kesalahan koneksi: %s\n", PQerrorMessage (conn));
exit (1);
}
while ( 1 )
{
fprintf(stdout, "\n\n\nDATA PASIEN\n");
fprintf(stdout, "***********\n\n");
fprintf(stdout, "a Tambah data\n");
fprintf(stdout, "b Tampil data\n");
fprintf(stdout, "x Keluar aplikasi\n");
fprintf(stdout, "Pilihan Anda: ");
c = tolower(fgetc (stdin));
menu = c;
while (c != '\n' && c != EOF) c = fgetc (stdin);
if (menu == 'a')
{
fprintf(stdout, "Tambah data\n");
fprintf(stdout, "===========\n");
fprintf(stdout, "Nama : ");
fgets (nama, MAX_LEN-1, stdin);
fprintf(stdout, "Alamat : ");
fgets (alamat, MAX_LEN-1, stdin);
sprintf (query, "insert into pasien (nama, alamat) values ('%s','%s')", nama, alamat);
res = PQexec (conn, query);
PQclear (res);
}
else
if (menu == 'b')
{
fprintf(stdout, "Tampil data\n");
fprintf(stdout, "===========\n");
sprintf (query, "select nama,alamat from pasien");
res = PQexec (conn, query);
field_count = PQnfields (res);
for (i=0; i< field_count; i++)
{
fprintf (stdout, "%-40s", PQfname (res, i));
}
fprintf (stdout, "\n");
rec_count = PQntuples (res);
for (i=0; i< rec_count; i++)
{
for (j=0; j< field_count; j++)
{
strcpy (temp, PQgetvalue (res, i, j));
temp[strlen(temp)-1] = 0;
fprintf (stdout, "%-40s", temp);
}
fprintf (stdout, "\n");
}
PQclear (res);
}
else
if (menu == 'x')
{
fprintf(stdout, "Bye\n");
break;
}
};
PQfinish (conn);
free (nama);
free (alamat);
free (query);
free (conninfo);
free (temp);
return 0;
}
示例4: SCIA_WR_SQL_CH4_TILE
/*+++++++++++++++++++++++++ Main Program or Function +++++++++++++++*/
void SCIA_WR_SQL_CH4_TILE( PGconn *conn, const char *prodName,
unsigned int num_rec,
const struct imap_rec *rec )
{
register unsigned int nr;
register unsigned int affectedRows = 0u;
char sql_query[SQL_STR_SIZE], cbuff[SQL_STR_SIZE];
char *pntr;
int nrow, numChar, meta_id;
long long tile_id;
PGresult *res;
/*
* check if product is already in database
*/
(void) snprintf( sql_query, SQL_STR_SIZE,
"SELECT pk_meta FROM %s WHERE name=\'%s\'",
META_TBL_NAME, prodName );
res = PQexec( conn, sql_query );
if ( PQresultStatus( res ) != PGRES_TUPLES_OK ) {
NADC_GOTO_ERROR( NADC_ERR_SQL, PQresultErrorMessage(res) );
}
if ( (nrow = PQntuples( res )) == 0 ) {
NADC_GOTO_ERROR( NADC_ERR_FATAL, prodName );
}
pntr = PQgetvalue( res, 0, 0 );
meta_id = (int) strtol( pntr, (char **) NULL, 10 );
PQclear( res );
/*
* Start a transaction block
*/
res = PQexec( conn, "BEGIN" );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
NADC_GOTO_ERROR( NADC_ERR_SQL, PQresultErrorMessage(res) );
PQclear( res );
/*
* insert all tiles in products
*/
for ( nr = 0; nr < num_rec; nr++ ) {
/* obtain next value for serial pk_tile */
res = PQexec( conn,
"SELECT nextval(\'tile_imap_ch4_pk_tile_seq\')" );
if ( PQresultStatus( res ) != PGRES_TUPLES_OK )
NADC_GOTO_ERROR( NADC_ERR_SQL, PQresultErrorMessage(res) );
pntr = PQgetvalue( res, 0, 0 );
tile_id = strtoll( pntr, (char **) NULL, 10 );
PQclear( res );
numChar = snprintf( sql_query, SQL_STR_SIZE, SQL_INSERT_TILE,
TILE_TBL_NAME, tile_id, meta_id, rec[nr].jday,
NINT(16 * rec[nr].meta.intg_time),
rec[nr].meta.elev,
rec[nr].ch4_vcd, rec[nr].ch4_error,
rec[nr].co2_vcd, rec[nr].co2_error,
rec[nr].ch4_vmr,
rec[nr].lon_corner[0],rec[nr].lat_corner[0],
rec[nr].lon_corner[1],rec[nr].lat_corner[1],
rec[nr].lon_corner[2],rec[nr].lat_corner[2],
rec[nr].lon_corner[3],rec[nr].lat_corner[3],
rec[nr].lon_corner[0],rec[nr].lat_corner[0] );
(void) fprintf( stderr, "%s [%-d]\n", sql_query, numChar );
if ( numChar >= SQL_STR_SIZE )
NADC_RETURN_ERROR( NADC_ERR_STRLEN, "sql_query" );
res = PQexec( conn, sql_query );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK ) {
NADC_ERROR( NADC_ERR_SQL, PQresultErrorMessage(res) );
PQclear( res );
res = PQexec( conn, "ROLLBACK" );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
NADC_ERROR( NADC_ERR_SQL, PQresultErrorMessage(res) );
goto done;
}
PQclear( res );
affectedRows += 1;
}
/*
* end the transaction
*/
res = PQexec( conn, "COMMIT" );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
NADC_ERROR( NADC_ERR_SQL, PQresultErrorMessage(res) );
done:
PQclear( res );
(void) snprintf( cbuff, SQL_STR_SIZE, "affectedRows=%-u", affectedRows );
NADC_ERROR( NADC_ERR_NONE, cbuff );
}
示例5: save_TUBii_command
void save_TUBii_command(client *c, int argc, sds *argv)
{
/* Update the TUBii state. */
uint32_t key;
PGconn *conn;
char conninfo[1024];
PGresult *res = NULL;
char command[10000];
//char* dbname="test", dbhost="", dbuser="", dbpass="";
sprintf(conninfo, "dbname=%s host=%s user=%s password=%s", dbconfig.name, dbconfig.host, dbconfig.user, dbconfig.password);
/* Now we update the database */
conn = PQconnectdb(conninfo);
if (PQstatus(conn) != CONNECTION_OK) {
addReplyErrorFormat(c, "connection to database failed: %s", PQerrorMessage(conn));
goto pq_error;
}
sprintf(command, "insert into TUBii ("
"control_reg, trigger_mask, speaker_mask, counter_mask,"
"caen_gain_reg, caen_channel_reg, lockout_reg, dgt_reg, dac_reg,"
"combo_enable_mask, combo_mask, counter_mode, clock_status,"
"prescale_value, prescale_channel, burst_rate, burst_channel"
") "
"VALUES ("
"%u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u, %u"
") "
"RETURNING key",
mReadReg((u32) MappedRegsBaseAddress, RegOffset10),
getTriggerMask(), getSpeakerMask(), getCounterMask(),
mReadReg((u32) MappedRegsBaseAddress, RegOffset11),
mReadReg((u32) MappedRegsBaseAddress, RegOffset12),
mReadReg((u32) MappedRegsBaseAddress, RegOffset14),
mReadReg((u32) MappedRegsBaseAddress, RegOffset15),
mReadReg((u32) MappedRegsBaseAddress, RegOffset13),
mReadReg((u32) MappedComboBaseAddress, RegOffset2),
mReadReg((u32) MappedComboBaseAddress, RegOffset3),
counter_mode, clockStatus(),
mReadReg((u32) MappedPrescaleBaseAddress, RegOffset2),
mReadReg((u32) MappedPrescaleBaseAddress, RegOffset3),
mReadReg((u32) MappedBurstBaseAddress, RegOffset2),
mReadReg((u32) MappedBurstBaseAddress, RegOffset3)
);
res = PQexec(conn, command);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
addReplyErrorFormat(c, "insert command failed: %s",
PQerrorMessage(conn));
goto pq_error;
}
if (PQnfields(res) != 1) {
addReplyError(c, "failed to get key from insert");
goto pq_error;
}
if (safe_strtoul(PQgetvalue(res, 0, 0), &key)) {
addReplyErrorFormat(c, "couldn't convert key from '%s' -> int", PQgetvalue(res, 0, 0));
goto pq_error;
}
PQclear(res);
PQfinish(conn);
addReply(c, ":%u", key);
return;
err:
addReplyError(c, tubii_err);
return;
pq_error:
if (res) PQclear(res);
PQfinish(conn);
}
示例6: sql_query
/*************************************************************************
*
* Function: sql_query
*
* Purpose: Issue a query to the database
*
*************************************************************************/
static int sql_query(SQLSOCK * sqlsocket, SQL_CONFIG *config, char *querystr) {
rlm_sql_postgres_sock *pg_sock = sqlsocket->conn;
int numfields = 0;
char *errorcode;
char *errormsg;
if (config->sqltrace)
radlog(L_DBG,"rlm_sql_postgresql: query:\n%s", querystr);
if (pg_sock->conn == NULL) {
radlog(L_ERR, "rlm_sql_postgresql: Socket not connected");
return SQL_DOWN;
}
pg_sock->result = PQexec(pg_sock->conn, querystr);
/*
* Returns a PGresult pointer or possibly a null pointer.
* A non-null pointer will generally be returned except in
* out-of-memory conditions or serious errors such as inability
* to send the command to the server. If a null pointer is
* returned, it should be treated like a PGRES_FATAL_ERROR
* result.
*/
if (!pg_sock->result)
{
radlog(L_ERR, "rlm_sql_postgresql: PostgreSQL Query failed Error: %s",
PQerrorMessage(pg_sock->conn));
/* As this error COULD be a connection error OR an out-of-memory
* condition return value WILL be wrong SOME of the time regardless!
* Pick your poison....
*/
return SQL_DOWN;
} else {
ExecStatusType status = PQresultStatus(pg_sock->result);
radlog(L_DBG, "rlm_sql_postgresql: Status: %s", PQresStatus(status));
switch (status) {
case PGRES_COMMAND_OK:
/*Successful completion of a command returning no data.*/
/*affected_rows function only returns
the number of affected rows of a command
returning no data...
*/
pg_sock->affected_rows = affected_rows(pg_sock->result);
radlog(L_DBG, "rlm_sql_postgresql: query affected rows = %i", pg_sock->affected_rows);
return 0;
break;
case PGRES_TUPLES_OK:
/*Successful completion of a command returning data (such as a SELECT or SHOW).*/
pg_sock->cur_row = 0;
pg_sock->affected_rows = PQntuples(pg_sock->result);
numfields = PQnfields(pg_sock->result); /*Check row storing functions..*/
radlog(L_DBG, "rlm_sql_postgresql: query affected rows = %i , fields = %i", pg_sock->affected_rows, numfields);
return 0;
break;
case PGRES_BAD_RESPONSE:
/*The server's response was not understood.*/
radlog(L_DBG, "rlm_sql_postgresql: Bad Response From Server!!");
return -1;
break;
case PGRES_NONFATAL_ERROR:
/*A nonfatal error (a notice or warning) occurred. Possibly never returns*/
return -1;
break;
case PGRES_FATAL_ERROR:
#if defined(PG_DIAG_SQLSTATE) && defined(PG_DIAG_MESSAGE_PRIMARY)
/*A fatal error occurred.*/
errorcode = PQresultErrorField(pg_sock->result, PG_DIAG_SQLSTATE);
errormsg = PQresultErrorField(pg_sock->result, PG_DIAG_MESSAGE_PRIMARY);
radlog(L_DBG, "rlm_sql_postgresql: Error %s", errormsg);
return check_fatal_error(errorcode);
#endif
break;
default:
/* FIXME: An unhandled error occurred.*/
/* PGRES_EMPTY_QUERY PGRES_COPY_OUT PGRES_COPY_IN */
//.........这里部分代码省略.........
示例7: begin_transaction
static int begin_transaction(db_con_t * _h, char *_s)
{
PGresult *mr;
int rv;
/*
** Note:
** The upper layers of code may attempt a transaction
** before opening or having a valid connection to the
** database. We try to sense this, and open the database
** if we have the sqlurl in the _h structure. Otherwise,
** all we can do is return an error.
*/
if(_h)
{
if(CON_CONNECTED(_h))
{
mr = PQexec(CON_CONNECTION(_h), "BEGIN");
if(!mr || PQresultStatus(mr) != PGRES_COMMAND_OK)
{
/*
** We get here if the connection to the
** db is corrupt, which can happen a few
** different ways, but all of them are
** related to the parent process forking,
** or being forked.
*/
PLOG("begin_transaction","corrupt connection");
CON_CONNECTED(_h) = 0;
}
else
{
/*
** this is the normal way out.
** the transaction ran fine.
*/
PQclear(mr);
return(0);
}
}
else
{
DLOG("begin_transaction", "called before db_init");
}
/*
** if we get here we have a corrupt db connection,
** but we probably have a valid db_con_t structure.
** attempt to open the db.
*/
if((rv = connect_db(_h, CON_SQLURL(_h))) != 0)
{
/*
** our attempt to fix the connection failed
*/
char buf[256];
sprintf(buf, "no connection, FATAL %d!", rv);
PLOG("begin_transaction",buf);
return(rv);
}
}
else
{
PLOG("begin_transaction","must call db_init first!");
return(-1);
}
/*
** we get here if the database connection was corrupt,
** i didn't want to use recursion ...
*/
mr = PQexec(CON_CONNECTION(_h), "BEGIN");
if(!mr || PQresultStatus(mr) != PGRES_COMMAND_OK)
{
char buf[256];
sprintf("FATAL %s, '%s'!\n",
PQerrorMessage(CON_CONNECTION(_h)), _s);
PLOG("begin_transaction", buf);
return(-1);
}
DLOG("begin_transaction", "db channel reset successful");
PQclear(mr);
return(0);
}
示例8: darkkernel_bdd_execute
/**
* query = select * from pg_database
*/
char darkkernel_bdd_execute(bdd *self,char *query)
{
PGresult *res;
char portal[1000],result=1;
int nFields;
int i,
j;
if (!self->conn)
self->connect(self);
if (!self->conn)
return 0;
/* Start a transaction block */
res = PQexec(self->conn, "BEGIN");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(self->conn));
PQclear(res);
self->disconnect(self);
result=0;
}
PQclear(res);
/*
* Fetch rows from pg_database, the system catalog of databases
*/
sprintf(portal, "DECLARE myportal CURSOR FOR %s\0", query);
res = PQexec(self->conn, portal);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "DECLARE CURSOR failed: %s", PQerrorMessage(self->conn));
PQclear(res);
PQfinish(self->conn);
}
PQclear(res);
res = PQexec(self->conn, "FETCH ALL in myportal");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
fprintf(stderr, "FETCH ALL failed: %s", PQerrorMessage(self->conn));
PQclear(res);
PQfinish(self->conn);
}
/* first, print out the attribute names */
nFields = PQnfields(res);
for (i = 0; i < nFields; i++)
printf("%-15s", PQfname(res, i));
printf("\n\n");
/* next, print out the rows */
for (i = 0; i < PQntuples(res); i++)
{
for (j = 0; j < nFields; j++)
printf("%-15s", PQgetvalue(res, i, j));
printf("\n");
}
PQclear(res);
/* close the portal ... we don't bother to check for errors ... */
res = PQexec(self->conn, "CLOSE myportal");
PQclear(res);
/* end the transaction */
res = PQexec(self->conn, "END");
PQclear(res);
self->disconnect(self);
return result;
}
示例9: zbx_db_vexecute
//.........这里部分代码省略.........
{
err = OCIStmtPrepare(stmthp, oracle.errhp, (text *)sql, (ub4)strlen((char *)sql),
(ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT);
}
if (OCI_SUCCESS == err)
{
err = OCIStmtExecute(oracle.svchp, stmthp, oracle.errhp, (ub4)1, (ub4)0,
(CONST OCISnapshot *)NULL, (OCISnapshot *)NULL, OCI_COMMIT_ON_SUCCESS);
if (OCI_SUCCESS == err)
{
ub4 nrows = 0;
err = OCIAttrGet((void *)stmthp, OCI_HTYPE_STMT, (ub4 *)&nrows,
(ub4 *)0, OCI_ATTR_ROW_COUNT, oracle.errhp);
ret = nrows;
}
}
if (OCI_SUCCESS != err)
{
zabbix_errlog(ERR_Z3005, err, zbx_oci_error(err), sql);
ret = (OCI_SERVER_NORMAL == OCI_DBserver_status() ? ZBX_DB_FAIL : ZBX_DB_DOWN);
}
if (NULL != stmthp)
{
(void)OCIHandleFree((dvoid *)stmthp, OCI_HTYPE_STMT);
stmthp = NULL;
}
#elif defined(HAVE_POSTGRESQL)
result = PQexec(conn,sql);
if (NULL == result)
{
zabbix_errlog(ERR_Z3005, 0, "result is NULL", sql);
ret = (CONNECTION_OK == PQstatus(conn) ? ZBX_DB_FAIL : ZBX_DB_DOWN);
}
else if (PGRES_COMMAND_OK != PQresultStatus(result))
{
error = zbx_dsprintf(error, "%s:%s",
PQresStatus(PQresultStatus(result)),
PQresultErrorMessage(result));
zabbix_errlog(ERR_Z3005, 0, error, sql);
zbx_free(error);
ret = (CONNECTION_OK == PQstatus(conn) ? ZBX_DB_FAIL : ZBX_DB_DOWN);
}
if (ZBX_DB_OK == ret)
ret = atoi(PQcmdTuples(result));
PQclear(result);
#elif defined(HAVE_SQLITE3)
if (0 == txn_level && PHP_MUTEX_OK != php_sem_acquire(&sqlite_access))
{
zabbix_log(LOG_LEVEL_CRIT, "ERROR: cannot create lock on SQLite3 database");
exit(FAIL);
}
lbl_exec:
if (SQLITE_OK != (err = sqlite3_exec(conn, sql, NULL, 0, &error)))
{
if (SQLITE_BUSY == err)
示例10: main
//.........这里部分代码省略.........
char *dbname = NULL;
char *host = NULL;
char *port = NULL;
char *username = NULL;
enum trivalue prompt_password = TRI_DEFAULT;
bool echo = false;
bool interactive = false;
PQExpBufferData sql;
PGconn *conn;
PGresult *result;
progname = get_progname(argv[0]);
set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts"));
handle_help_version_opts(argc, argv, "dropdb", help);
while ((c = getopt_long(argc, argv, "h:p:U:wWei", long_options, &optindex)) != -1)
{
switch (c)
{
case 'h':
host = optarg;
break;
case 'p':
port = optarg;
break;
case 'U':
username = optarg;
break;
case 'w':
prompt_password = TRI_NO;
break;
case 'W':
prompt_password = TRI_YES;
break;
case 'e':
echo = true;
break;
case 'i':
interactive = true;
break;
default:
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
}
}
switch (argc - optind)
{
case 0:
fprintf(stderr, _("%s: missing required argument database name\n"), progname);
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
case 1:
dbname = argv[optind];
break;
default:
fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
progname, argv[optind + 1]);
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
}
if (interactive)
{
printf(_("Database \"%s\" will be permanently removed.\n"), dbname);
if (!yesno_prompt("Are you sure?"))
exit(0);
}
initPQExpBuffer(&sql);
appendPQExpBuffer(&sql, "DROP DATABASE %s;\n",
fmtId(dbname));
/*
* Connect to the 'postgres' database by default, except have
* the 'postgres' user use 'template1' so he can drop the
* 'postgres' database.
*/
conn = connectDatabase(strcmp(dbname, "postgres") == 0 ? "template1" : "postgres",
host, port, username, prompt_password, progname);
if (echo)
printf("%s", sql.data);
result = PQexec(conn, sql.data);
if (PQresultStatus(result) != PGRES_COMMAND_OK)
{
fprintf(stderr, _("%s: database removal failed: %s"),
progname, PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
PQclear(result);
PQfinish(conn);
exit(0);
}
示例11: Q_UNUSED
bool QgsShapeFile::insertLayer( QString dbname, QString schema, QString primary_key, QString geom_col,
QString srid, PGconn * conn, QProgressDialog& pro, bool &fin,
QString& errorText )
{
Q_UNUSED( dbname );
connect( &pro, SIGNAL( canceled() ), this, SLOT( cancelImport() ) );
import_canceled = false;
bool result = true;
QString query = QString( "CREATE TABLE %1.%2(%3 SERIAL PRIMARY KEY" )
.arg( QgsPgUtil::quotedIdentifier( schema ) )
.arg( QgsPgUtil::quotedIdentifier( table_name ) )
.arg( QgsPgUtil::quotedIdentifier( primary_key ) );
for ( uint n = 0; n < column_names.size() && result; n++ )
{
query += QString( ",%1 %2" )
.arg( QgsPgUtil::quotedIdentifier( column_names[n] ) )
.arg( column_types[n] );
}
query += " )";
QgsDebugMsg( "Query string is: " + query );
PGresult *res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
// flag error and send query and error message to stdout on debug
errorText += tr( "The database gave an error while executing this SQL:\n%1\nThe error was:\n%2\n" )
.arg( query ).arg( PQresultErrorMessage( res ) );
PQclear( res );
return false;
}
else
{
PQclear( res );
}
query = QString( "SELECT AddGeometryColumn(%1,%2,%3,%4,%5,2)" )
.arg( QgsPgUtil::quotedValue( schema ) )
.arg( QgsPgUtil::quotedValue( table_name ) )
.arg( QgsPgUtil::quotedValue( geom_col ) )
.arg( srid )
.arg( QgsPgUtil::quotedValue( geom_type ) );
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_TUPLES_OK )
{
errorText += tr( "The database gave an error while executing this SQL:\n%1\nThe error was:\n%2\n" )
.arg( query ).arg( PQresultErrorMessage( res ) );
PQclear( res );
return false;
}
else
{
PQclear( res );
}
if ( isMulti )
{
query = QString( "select constraint_name from information_schema.table_constraints where table_schema=%1 and table_name=%2 and constraint_name in ('$2','enforce_geotype_the_geom')" )
.arg( QgsPgUtil::quotedValue( schema ) )
.arg( QgsPgUtil::quotedValue( table_name ) );
QStringList constraints;
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) == PGRES_TUPLES_OK )
{
for ( int i = 0; i < PQntuples( res ); i++ )
constraints.append( PQgetvalue( res, i, 0 ) );
}
PQclear( res );
if ( constraints.size() > 0 )
{
// drop the check constraint
// TODO This whole concept needs to be changed to either
// convert the geometries to the same type or allow
// multiple types in the check constraint. For now, we
// just drop the constraint...
query = QString( "alter table %1 drop constraint %2" )
.arg( QgsPgUtil::quotedIdentifier( table_name ) )
.arg( QgsPgUtil::quotedIdentifier( constraints[0] ) );
res = PQexec( conn, query.toUtf8() );
if ( PQresultStatus( res ) != PGRES_COMMAND_OK )
{
errorText += tr( "The database gave an error while executing this SQL:\n%1\nThe error was:\n%2\n" )
.arg( query ).arg( PQresultErrorMessage( res ) );
PQclear( res );
return false;
}
PQclear( res );
}
}
//.........这里部分代码省略.........
示例12: sql_exec
/*
* Actual code to make call to the database and print the output data.
*/
int
sql_exec(PGconn *conn, const char *todo, bool quiet)
{
PGresult *res;
int nfields;
int nrows;
int i,
j,
l;
int *length;
char *pad;
/* make the call */
res = PQexec(conn, todo);
/* check and deal with errors */
if (!res || PQresultStatus(res) > 2)
{
fprintf(stderr, "oid2name: query failed: %s\n", PQerrorMessage(conn));
fprintf(stderr, "oid2name: query was: %s\n", todo);
PQclear(res);
PQfinish(conn);
exit(-1);
}
/* get the number of fields */
nrows = PQntuples(res);
nfields = PQnfields(res);
/* for each field, get the needed width */
length = (int *) pg_malloc(sizeof(int) * nfields);
for (j = 0; j < nfields; j++)
length[j] = strlen(PQfname(res, j));
for (i = 0; i < nrows; i++)
{
for (j = 0; j < nfields; j++)
{
l = strlen(PQgetvalue(res, i, j));
if (l > length[j])
length[j] = strlen(PQgetvalue(res, i, j));
}
}
/* print a header */
if (!quiet)
{
for (j = 0, l = 0; j < nfields; j++)
{
fprintf(stdout, "%*s", length[j] + 2, PQfname(res, j));
l += length[j] + 2;
}
fprintf(stdout, "\n");
pad = (char *) pg_malloc(l + 1);
MemSet(pad, '-', l);
pad[l] = '\0';
fprintf(stdout, "%s\n", pad);
free(pad);
}
/* for each row, dump the information */
for (i = 0; i < nrows; i++)
{
for (j = 0; j < nfields; j++)
fprintf(stdout, "%*s", length[j] + 2, PQgetvalue(res, i, j));
fprintf(stdout, "\n");
}
/* cleanup */
PQclear(res);
free(length);
return 0;
}
示例13: PQexec
static PGresult *c_psql_exec_query_noparams (c_psql_database_t *db,
udb_query_t *q)
{
return PQexec (db->conn, udb_query_get_statement (q));
} /* c_psql_exec_query_noparams */
示例14: GenSQL
void
GenSQL (PGconn *dbh,const char *file)
{
int i,ntuples;
int reverse=0;
int type_check=0;
int preamble=0;
PGresult *result;
Oid col_type;
FILE *out;
char token_data[TOKEN_DATA_LEN+1];
char token_type[TOKEN_TYPE_LEN+1];
unsigned long long token;
memset((void *)token_type, 0, TOKEN_TYPE_LEN+1);
memset((void *)token_data, 0, TOKEN_DATA_LEN+1);
if (strncmp(file,"-",1)==0) {
out=stdout;
} else {
if ( (out = fopen(file,"w+")) == NULL ) {
fprintf(stderr, "Failed to open file %s for writing - %s\n",
file, strerror(errno));
PQfinish(dbh);
exit(EXIT_FAILURE);
}
}
result = PQexec(dbh, "SELECT uid, token, spam_hits, innocent_hits, last_hit "
"FROM dspam_token_data");
if (! result || PQresultStatus(result) != PGRES_TUPLES_OK) {
fprintf(stderr, "Failed to run result: %s\n", PQresultErrorMessage(result));
if (result) PQclear(result);
PQfinish(dbh);
fclose (out);
exit(EXIT_FAILURE);
}
ntuples = PQntuples(result);
for (i=0; i<ntuples; i++)
{
if (!type_check)
{
type_check = 1;
col_type = PQftype(result, 1);
if (col_type == BIGINTOID)
{
fprintf(stderr, "Datatype of dspam_token_data.token *not* NUMERIC;\n"
"assuming that you want to revert back to NUMERIC(20) type from BIGINT type\n");
reverse=1;
} else if (col_type != NUMERICOID)
{
fprintf(stderr, "Type of dspam_token_data.token is not BIGINT *or* NUMERIC(20)!\n"
"I have got no clue of how to deal with this and I am going to sulk now.\n");
if (result) PQclear(result);
PQfinish(dbh);
fclose (out);
exit(EXIT_FAILURE);
}
}
if (!preamble)
{
preamble = 1;
if (reverse == 0) {
snprintf(token_type, TOKEN_TYPE_LEN, "bigint");
} else {
snprintf(token_type, TOKEN_TYPE_LEN, "numeric(20)");
}
fprintf(out,"BEGIN;\n"
"DROP TABLE dspam_token_data;\n"
"COMMIT;\n"
"BEGIN;\n"
"CREATE TABLE dspam_token_data (\n"
" uid smallint,\n"
" token %s,\n"
" spam_hits int,\n"
" innocent_hits int,\n"
" last_hit date,\n"
" UNIQUE (token, uid)\n"
") WITHOUT OIDS;\n"
"COMMIT;\n"
"BEGIN;\n"
"COPY dspam_token_data (uid,token,spam_hits,innocent_hits,last_hit) FROM stdin;\n"
, token_type);
}
if (!reverse) {
token = strtoull( PQgetvalue(result,i,1), NULL, 0);
snprintf(token_data, TOKEN_DATA_LEN, "%lld", token);
} else {
token = (unsigned long long) strtoll( PQgetvalue(result,i,1), NULL, 0);
snprintf(token_data, TOKEN_DATA_LEN, "%llu", token);
}
fprintf(out,"%s\t%s\t%s\t%s\t%s\n",
PQgetvalue(result,i,0), token_data,
PQgetvalue(result,i,2),
PQgetvalue(result,i,3),
PQgetvalue(result,i,4) );
}
if (result) PQclear(result);
fprintf(out, "\\.\n\n"
"COMMIT;\n"
//.........这里部分代码省略.........
示例15: SendQuery
/*
* SendQuery: send the query string to the backend
* (and print out results)
*
* Note: This is the "front door" way to send a query. That is, use it to
* send queries actually entered by the user. These queries will be subject to
* single step mode.
* To send "back door" queries (generated by slash commands, etc.) in a
* controlled way, use PSQLexec().
*
* Returns true if the query executed successfully, false otherwise.
*/
bool
SendQuery(const char *query)
{
PGresult *results;
PGTransactionStatusType transaction_status;
double elapsed_msec = 0;
bool OK = false;
bool on_error_rollback_savepoint = false;
static bool on_error_rollback_warning = false;
if (!pset.db)
{
psql_error("You are currently not connected to a database.\n");
goto sendquery_cleanup;
}
if (pset.singlestep)
{
char buf[3];
printf(_("***(Single step mode: verify command)*******************************************\n"
"%s\n"
"***(press return to proceed or enter x and return to cancel)********************\n"),
query);
fflush(stdout);
if (fgets(buf, sizeof(buf), stdin) != NULL)
if (buf[0] == 'x')
goto sendquery_cleanup;
}
else if (pset.echo == PSQL_ECHO_QUERIES)
{
puts(query);
fflush(stdout);
}
if (pset.logfile)
{
fprintf(pset.logfile,
_("********* QUERY **********\n"
"%s\n"
"**************************\n\n"), query);
fflush(pset.logfile);
}
SetCancelConn();
transaction_status = PQtransactionStatus(pset.db);
if (transaction_status == PQTRANS_IDLE &&
!pset.autocommit &&
!command_no_begin(query))
{
results = PQexec(pset.db, "BEGIN");
if (PQresultStatus(results) != PGRES_COMMAND_OK)
{
psql_error("%s", PQerrorMessage(pset.db));
PQclear(results);
ResetCancelConn();
goto sendquery_cleanup;
}
PQclear(results);
transaction_status = PQtransactionStatus(pset.db);
}
if (transaction_status == PQTRANS_INTRANS &&
pset.on_error_rollback != PSQL_ERROR_ROLLBACK_OFF &&
(pset.cur_cmd_interactive ||
pset.on_error_rollback == PSQL_ERROR_ROLLBACK_ON))
{
if (on_error_rollback_warning == false && pset.sversion < 80000)
{
psql_error("The server (version %d.%d) does not support savepoints for ON_ERROR_ROLLBACK.\n",
pset.sversion / 10000, (pset.sversion / 100) % 100);
on_error_rollback_warning = true;
}
else
{
results = PQexec(pset.db, "SAVEPOINT pg_psql_temporary_savepoint");
if (PQresultStatus(results) != PGRES_COMMAND_OK)
{
psql_error("%s", PQerrorMessage(pset.db));
PQclear(results);
ResetCancelConn();
goto sendquery_cleanup;
}
PQclear(results);
on_error_rollback_savepoint = true;
}
//.........这里部分代码省略.........