-
问题描述
PostgreSQL在插入带有单引号的字符串时,必须在单引号前面再加一个单引号,否则插入数据会出错。 -
解决思路举例
INSERT INTO "public"."student"("id", "name") VALUES(1, 'da''hai');
INSERT INTO "public"."student"("id", "name") VALUES(1, E'da\'hai');
- C++实现在带有单引号的字符串的单引号前再加一个单引号
#include <iostream>
#include <list>
using namespace std;
/*
查找、替换和插入字符串
*/
/*
由于PostgreSQL在插入带有单引号的字符串时,必须在单引号前面再加一个单引号,否则插入数据会出错。
INSERT INTO "public"."student"("id", "name") VALUES(1, 'da''hai');
INSERT INTO "public"."student"("id", "name") VALUES(1, E'da\'hai');
*/
/// <summary>
/// 在带有单引号的字符串的单引号前再加一个单引号
/// </summary>
/// <param name="str">带有单引号(英文)的字符串</param>
/// <returns>返回std::string</returns>
std::string addSingleQuotationMark(std::string str)
{
std::list<int> pos_list;
std::list<int>::iterator iter_pos;
for(size_t i = 0; i < str.size(); i++)
{
int pos = str.find("'", i);
if(pos > -1){
pos_list.push_back(pos);
}
}
//去掉重复的元素
pos_list.unique();
int k = 0;
for(iter_pos = pos_list.begin(); iter_pos != pos_list.end(); iter_pos++)
{
str.insert(*iter_pos + k, "'");
k++;
}
return str;
}
int main()
{
string str = "N'SGOM'A'";
cout << addSingleQuotationMark(str) << endl;
string aa = "123'456";
cout << addSingleQuotationMark(aa) << endl;
cout << addSingleQuotationMark("") << endl;
int pos = str.find("'", 0);
if(pos > -1)
{
//替换字符
str.replace(pos, pos, "*");
cout << "str=" << str << endl;
//插入字符
str.insert(pos, "'");
cout << "str=" << str << endl;
}
return 0;
}