c++ mysql中单引号的处理(替换)

来源:互联网 发布:网络免费短信平台 编辑:程序博客网 时间:2024/05/16 00:51

使用mysql数据库中,经常因为用户输入的内容中包含单引号而导致mysql执行插入等操作时报错。

经过查询,通用的方法是将用户输入的单引号用两个单引号代替,ex:

i'm a boy 可以再处理插入语句时拼做 i''(此处是两个单引号,不是一个双引号)m a boy。

那么该如何将语句中的单引号改成双引号呢,c++只提供了最原始的更改操作replace.

我提供的方法是:

string replace_new(string srcstr,string oldstr,string newstr)
{
size_t last = 0;
size_t index = 0;
while((index = srcstr.find_first_of(oldstr,last)) != srcstr.npos)
{
srcstr.replace(index,oldstr.length(),newstr);
last = index + newstr.length();
}
return srcstr;
}

引用到mysql语句处理如main():

int main(int argc,char argv[])
{
string srcstr = "abc'def'gh'j'ddd'";


cout << "src str is: " << srcstr << endl;
cout << "after replaced is:" << replace_new(srcstr,"\'","\'\'") << endl; //第一个参数为原始字符串,第二个参数为转义单引号字符串,第三个为转义两个单引号字符串;

getchar();
}


如果问题,希望大家指正!

0 0
原创粉丝点击