I am working with C programming language and using Postgres database to insert records. One of the columns of the table in the database is of type timestamp
. The data I am getting in the C program is of type int64_t
and I need to pass this value as a parameter in the INSERT
statement like shown below. In order to do that, I tried to convert the int64_t
value to a string using sprintf()
.
char str[21];
sprintf(str, "%" PRId64 "\n", someTimeReceived inTheProgram);
const char * const paramValues[1] = { str };
PGresult *res = res = PQexecParams(
conn,
"INSERT INTO dummy VALUES(1,to_timestamp($1)::timestamp)",
1, /* one parameter */
NULL,
paramValues,
NULL, /* parameter lengths are not required for strings */
NULL, /* all parameters are in text format */
0 /* result shall be in text format */
);
But on using sprintf()
, some garbage value are being inserted at the end of string. For example if the received int64_t
value is 132408394771256230
then sprintf()
is converting it to 132408394771256230\n\0\003
. Because of the extra garbage values appended at the end of string, the program fails to insert the given value and then terminates.