在传递给mysql_query之前,有效地转义C中的引号

时间:2011-10-20 17:23:24

标签: mysql sql c

简而言之,我通常使用sprintf

在C中构建MySQL查询

sprintf(sqlcmd,"update foo set dog=\"lab\" where description=\"%s\"",some_desc);
mysql_query(some_conn,sqlcmd);

然而,如果some_desc类似于 Crazy 5“Dog ,那么MySql Server会尖叫,因为它对悬挂的引用感到困惑。

最好是在C中扫描some_desc替换“with”“,或者MySql中是否有一个函数可以更好地包装它...即description = string(Crazy 5”Dog)?

谢谢!

3 个答案:

答案 0 :(得分:6)

虽然MySQL有mysql_real_escape_string()功能,但您可能应该使用prepared statements代替,这可以让您使用?占位符而不是实际参数,然后在每次执行语句之前将它们绑定到实际参数。

答案 1 :(得分:3)

答案 2 :(得分:-2)

我会编写一个简单的转义函数,如下所示:

size_t escape_mysql_string(const char * input, size_t input_size,
   char * output, size_t output_size)
{
   unsigned long ipos; // position within input buffer
   unsigned long opos; // position within output buffer

   // quick check to verify output buffer is at least as large as input buffer
   if (output_size < (input_size+2))
      return(0);

   // loop through input buffer
   opos = 0;
   for(ipos = 0; ((ipos < input_size) && (input[ipos])); ipos++)
   {
      // verify that output buffer has room for escaped input
      if ((opos+2) >= output_size)
      {
         output[opos] = '\0';
         return(opos);
      };

      switch(input[ipos])
      {
         // escape ("""), ("'"), ("\"), ("%"), and ("_") characters
         case '\'':
         case '\"':
         case '\\':
         case '%':
         case '_':
         output[opos] = '\\';
         opos++;
         output[opos] = input[ipos];
         break;

         // escape newlines
         case '\n':
         output[opos] = '\\';
         opos++;
         output[opos] = 'n';
         break;

         // escape carriage returns
         case '\r':
         output[opos] = '\\';
         opos++;
         output[opos] = 'r';
         break;

         // escape tabs
         case '\t':
         output[opos] = '\\';
         opos++;
         output[opos] = 't';
         break;

         // save unescapd input character
         default:
         output[opos] = input[ipos];
         break;
      };
      opos++;
   };

   output[opos] ='\0';
   return(opos);
}

用以下内容调用它:

char some_escaped_desc[1024];
escape_mysql_string(some_desc, strlen(some_desc), some_escaped_desc, 1024);