Skip to Content.
Sympa Menu

freetds - Re: Escape string function

freetds AT lists.ibiblio.org

Subject: FreeTDS Development Group

List archive

Chronological Thread  
  • From: ZIGLIO Frediano <Frediano.Ziglio AT vodafoneomnitel.it>
  • To: "'TDS Development Group'" <freetds AT franklin.metalab.unc.edu>
  • Subject: Re: Escape string function
  • Date: Thu, 11 Jul 2002 17:47:52 +0200


>
> not much to it really. The biggest problem is do you have the buffer
> space big enough to handle the escaped string, here's a quick
> and dirty
> implementation, calling program is responsible for free()ing
> the string
> when done. The API's don't really do much of anything with
> the SQL, they
> just take it directly from the application and pass it on to
> the server
> without processing, so I suppose that is why nothing is there.
>
> char *escape_string(char *instr)
> {
> char *outstr;
> int i, j=0, need = 0;
>
> for (i=0;i<strlen(instr);i++)
> if (instr[i]=='\'') need++;
>
> outstr = malloc(strlen(outstr) + need + 1);
>
> for (i=0;i<strlen(instr);i++) {
> if (instr[i]=='\'') {
> outstr[j++]='\'';
> outstr[j++]=instr[i];
> }
> return outstr;
> }
>
>
> This of course assumes that you are using single quotes for string
> literals. Sybase allows use of double quotes if
> quoted_indentifier is set
> to off (which it is by default) but it's non-portable and
> make break in
> the future (jConnect turns it off on connect for instance).
>
> Brian
>

I prefer also to handle NULL case and quote all string

/**
* Escape a string using SQL syntax
* Return NULL if out of memory
*/
char *escape_string(const char *instr)
{
char *outstr, *pdst;
const char *psrc;
int need;

/* null string, return NULL */
if (!instr)
return strdup("NULL");

need = 0;
for (psrc=instr; *psrc; ++psrc,++need)
if (*psrc=='\'') ++need;

outstr = malloc(need + 3);
if (!outstr) return NULL;
pdst = outstr;

*pdst++ = '\'';
for (psrc=instr; *psrc; ++psrc) {
if (*psrc=='\'') {
*pdst++='\'';
*pdst++ = *psrc;
}
*pdst++ = '\'';
*pdst++ = '\0';
return outstr;
}

Perhaps some other optimization can be done...
I have also a version of a sqlnprintf...

freddy77

=================================
"STRICTLY PERSONAL AND CONFIDENTIAL

This message may contain confidential and proprietary material for the sole
use of the intended recipient. Any review or distribution by others is
strictly prohibited. If you are not the intended recipient please contact
the sender and delete all copies.
The contents of this message that do not relate to the official business of
our company shall be understood as neither given nor endorsed by it."

=================================




Archive powered by MHonArc 2.6.24.

Top of Page