Question

I can update record in table by string manipulation which have some weakness.
So, now I'm try to update with parameters but this don't go as I thought.

sprintf(sql, "%s%s%s%s%s%d%s",
    "UPDATE ", mytable, " SET ",
    "my_id=$0, mystr1=$1, mystr2=$2, myint=$3, mydouble=$4",
    "WHERE my_id='", local_my_id, "'");

const char *values[5] =
{local_my_id, local_mystr1, local_mystr2, local_myint, local_mydouble};

result = PQexecParams(conn, sql, 5, NULL, values,  NULL,  NULL, 0);

Values 1 and 4 are integers and value 5 is double what don't fit into const char array.
I try a same with strings only and it works.

If I have to convert numbers to strings that don't seem's logical.

How to do this properly?

Was it helpful?

Solution

It might not seem logical to need to convert numbers to strings, but that is exactly what you must do if you're using the default "text" protocol. Consider using the libpqtypes library, which takes care of lots of this detail for you.

You can use the binary protocol (on a param-by-param basis, see the documentation on PQexecParams) ... but in general you're way better off using the text protocol. It's often actually faster on the network, particularly for lots of small numbers, and you don't have to worry about endianness and number format issues if you use the text protocol.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top