Tom Lane wrote:
> Now, as to mechanism, what I currently do is to define a function
> const char * SQLstring (const char * str)
> which returns "NULL" if str is NULL, otherwise the string surrounded
> with single quotes and having internal special characters escaped.
> Then the SQL statement is constructed with
> sprintf(query, "update tablename set comment = %s where ...",
> SQLstring(str), ...);
> Notice that by having the quotes stuck on by SQLstring, not by the printf
> format, I can deal easily with null field values.
>
> This is a lot easier to get right in C++, where the function can return
> a temporary string object that will get deallocated automatically after
> use. In C the most reasonable way to proceed is to have SQLstring
> return a pointer to a static area, which means you can't invoke
To get out of this, the function SQLstring(char *str) could
use malloc'ed memory to return it's result and remember all
the chunks that it allocated in some static held array. After
all, another function SQLstring_free() might be called that
has to tidy up. The array itself is also malloc'ed and can
grow if many strings are used.
Still not that pretty, but it's half way of automation. And
if the SQLstring_free() is forgotten once, never mind - the
next call will do it anyway.
Jan
--
#======================================================================#
# It's easier to get forgiveness for being wrong than for being right. #
# Let's break this rule - forgive me. #
#======================================== jwieck@debis.com (Jan Wieck) #