2014-03-25 36 views
0

我使用PQexecParams功能做SQL請求到PostgreSQL數據庫:與sprintf的重用緩衝區指針和PQexecParams

PGresult *PQexecParams(PGconn *conn, 
        const char *command, 
        int nParams, 
        const Oid *paramTypes, 
        const char * const *paramValues, 
        const int *paramLengths, 
        const int *paramFormats, 
        int resultFormat); 

要通過paramValues,我用sprintf:

sprintf(buffer1, "%d", stats.packets_count); 
values2[0] = buffer1; 
sprintf(buffer2, "%d", stats.packets_count_gap); 
values2[1] = buffer2; 
sprintf(buffer3, "%f", stats.packets_mean); 
values2[2] = buffer3; 
sprintf(buffer4, "%f", stats.variance); 
values2[3] = buffer4; 
sprintf(buffer5, "%f", stats.square_mean); 
values2[4] = buffer5; 
sprintf(buffer6, "%f", stats.standard_deviation); 
values2[5] = buffer6; 
sprintf(buffer7, "%d", stats.is_ddos); 
values2[6] = buffer7; 
sprintf(buffer8, "%f", stats.threshold); 
values2[7] = buffer8; 
sprintf(buffer9, "%d", stats.bandwidth); 
values2[8] = buffer9; 
values2[9] = proto_name; 
sprintf(buffer11, "%f", packet_proto_ratio); 
values2[10] = buffer11; 
sprintf(buffer12, "%f", tcp_sign_ratio); 
values2[11] = buffer12; 
sprintf(buffer13, "%d", inflow_outflow_gap); 
values2[12] = buffer13; 
sprintf(buffer14, "%f", bandwidth_ratio); 
values2[13] = buffer14; 

這裏是要求:

result = PQexecParams(psql, "INSERT INTO statistics (packets_count, packets_count_gap, mean, variance, square_mean, standard_deviation, is_ddos, date, threshold, bandwidth, protocol, packet_proto_ratio, tcp_sign_ratio, inflow_outflow_gap, bandwidth_ratio) VALUES ($1, $2, $3, $4, $5, $6, $7, now(), $8, $9, $10, $11, $12, $13, $14);", 14, NULL, values2, lengths2, NULL, 0); 

但它感覺真的很髒,這樣做,有沒有什麼辦法可以重用一個單一的BU指針?因爲我在我的代碼中有幾個需要執行sql請求的地方,所以我最終得到了很多緩衝區。

謝謝!

回答

3

每個緩衝區都指向一個單獨的內存塊,並有一個單獨的值。所以不,你不能重用它們。在將它們發送到PostgreSQL服務器之前,它們必須全部保持有效且完整。

你可以做什麼 - 如果你知道總數據集有多大 - 是分配一個單獨的緩衝區。然後按照每次向其追加數據寫入的數據長度提前寫入指針。因此,values數組中的所有指針都指向同一客戶端緩衝區中不同的,不重疊的部分。

這很簡單,因爲sprintf返回打印的字符數,不包括空終止符。