Mysql string escape function bitsCN.com
Insert a data table in mysql. if the data contains '/', it may cause a syntax error. you don't need to explain this. you know, you need to write an escape function. at the beginning, you want to directly use the string replace, however, this method must be called three times.
The efficiency on the server is too low, so I wrote it in C, and it feels okay. The time complexity is irrelevant to the number of characters to be escaped. if the source string does not match, the copy operation is not required.
// Escape function, convert /'
Bool ConverToDBStr (const char * src, char * dst)
{
Int I =-1; // record the last matched position
Int dOffset = 0; // destination string cursor
Int nCopy = 0; // The number of bytes to be copied this time
Const char * p = src;
While (* p)
{
If (* p = '//' | * p = '/''| * p = '"')
{
NCopy = p-src-i-1;
Memcpy (dst + dOffset, src + I + 1, nCopy );
DOffset + = nCopy;
* (Dst + Offset) = '//';
* (Dst + dOffset + 1) = * p;
DOffset + = 2;
I = p-src;
}
P ++;
}
If (dOffset> 0) // matched, copy the final string
{
Memcpy (dst + dOffset, src + I + 1, p-src-I );
Return true;
}
Return false;
}
As you can see, replace can be implemented with this function slightly changed.
Author: ifeng
BitsCN.com