During database insertion, if you use the insert statement to insert content to a varchar field, an error is reported because the length of the inserted content exceeds the specified length. In particular, when inserting a mix of Chinese and English strings, SQL Server generally occupies two bytes of Chinese characters. Therefore, a mixed string must be processed, and the length of the string is calculated in bytes. The method is as follows:
/// <Summary>
/// Obtain a mix of Chinese and English strings with a specified byte length
/// </Summary>
Private string getstring (string STR, int Len)
{
String result = string. Empty; // The final returned result.
Int bytelen = system. Text. encoding. Default. getbytecount (STR); // length of a single byte
Int charlen = Str. length; // String Length when the characters are treated equally
Int bytecount = 0; // record the read progress
Int Pos = 0; // record position
If (bytelen> Len)
{
For (INT I = 0; I <charlen; I ++)
{
If (convert. toint32 (Str. tochararray () [I])> 255) // calculate by Chinese Character and add 2
Bytecount + = 2;
Else // Add 1 to the English character
Bytecount + = 1;
If (bytecount> Len) // when the value exceeds the upper limit, only the previous valid position is recorded.
{
Pos = I;
Break;
}
Else if (bytecount = Len) // write down the current location
{
Pos = I + 1;
Break;
}
}
If (Pos> = 0)
Result = Str. substring (0, POS );
}
Else
Result = STR;
Return result;
}