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請求的地方,所以我最終得到了很多緩衝區。
謝謝!