sqlite 关于 string 类型的数据需要转义。

通过查找规则,可以很容易通过switch拼装一个字符串来搞定。 大致规则是,单引号和双引号要变成两个,其他特殊字符为前面加上'/'。

C语言实现如下:

char *str_escape(const char *str) {
  static char dest[1024];
  int i;
  int j = 0;
  int len = strlen(str);
  for (i = 0; i < len; i++) {
    switch (str[i]) {
      case '\'':
      case '\"':
        dest[j] = dest[j + 1] = str[i];
        j += 2;
        break;
      case '/':
      case '[':
      case ']':
      case '%':
      case '&':
      case '_':
      case '(':
      case ')':
        dest[j] = '/';
        j++;
      default:
        dest[j] = str[i];
        j++;
    }
  }
  dest[j] = '\0';
  return dest;
}

看起来很好很强大。

又手贱 google 了下更多相关信息,发现前面那个函数可以替换为如下:

inline char *str_escape(const char *str) {  //
  return sqlite3_mprintf("%q", str);
}

没错,人家已经给了系统函数了。

References:

Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

1 Comment

Leniy · April 16, 2013 at 09:12

Google Chrome 26.0.1410.64 Google Chrome 26.0.1410.64 Windows 7 Windows 7

哇咔咔

Leave a Reply to Leniy Cancel reply

Your email address will not be published. Required fields are marked *