2012-01-24 4 views

risposta

10

Ci sono 2 tipi di blob in PostgreSQL — BYTEA e Large Objects. Ti consiglio di non utilizzare oggetti di grandi dimensioni poiché non puoi unirli alle tabelle.

Per bytea usereste qualcosa di simile in libpq:

PGresult* put_data_to_tablename(
    PGconn* conn, 
    int32_t id, 
    int data_size, 
    const char* const data 
) { 
    PGresult* result; 
    const uint32_t id_big_endian = htonl((uint32_t)id); 
    const char* const paramValues[] = { &id_big_endian, data }; 
    const int nParams = sizeof(paramValues)/sizeof(paramValues[0]); 
    const int paramLenghts[] = { sizeof(id_big_endian), data_size }; 
    const int paramFormats[] = { 1, 1 }; /* binary */ 
    const int resultFormat = 0; /* text */ 

    result = PQexecParams(
    conn, 
    "insert into tablename (id, data) values ($1::integer, $2::bytea)", 
    nParams, 
    NULL, /* Types of parameters, unused as casts will define types */ 
    paramValues, 
    paramLenghts, 
    paramFormats, 
    resultFormat 
); 
    return result; 
} 
1

Utilizzando libpqxx è il modo per farlo C++, mentre libpq è l'API C.

Ecco un esempio completo di come farlo utilizzando pqxx: How to insert binary data into a PostgreSQL BYTEA column using the C++ libpqxx API?

In breve, il relativo C linee ++ utilizzando libpqxx simile a questa:

void * bin_data = ...; // obviously do what you need to get the binary data... 
size_t bin_size = ...; // ...and the size of the binary data 
pqxx::binarystring bin(bin_data, bin_size); 
pqxx::result r = work.prepared("test")(bin).exec(); 
work.commit(); 
+1

Worth c'è di nota sono l'invecchiamento problemi con libpqxx, e no, non è il post ufficiale "postgresql C++ api" come afferma sul sito. – user3791372

Problemi correlati