天天看點

将特殊字元插入資料庫

最近測試的發現有的插入資料庫的資訊會丢失,一直不清楚怎麼回事;今天仔細看了下資料庫才知道一些特殊字元是不能直接插入資料庫的,比如單引号在資料庫語句中表示引用其他字元,如果向資料庫直接插入“Tom's cat”這樣的字元串就會失敗。

那麼這種情況要怎麼解決呢?查了一下資料一般有兩種方案:一種是先對字元串進行轉義,然後插入資料庫,這是根本的解決方案;還有一種不那麼“本質”但是相當漂亮的方法,先對字元串進行編碼,然後取出時解碼。

第一種方案一下子沒有找到iOS版的代碼,隻有Java版的;繼續嘗試第二種方案,存入時沒什麼問題,取出時卻是資料對應的字元串,雖然有辦法轉化,但是感覺還是太麻煩,想想還是自己寫第一種方案的代碼吧。

代碼很簡單,參考了網上的轉化方式,但是确實可以直接插入資料庫了:

<span style="color:#006600;background-color: rgb(255, 255, 255);">+ (NSString *)sqlStringFromString:(NSString *)string
{
    NSString *sqlText;
    if (string.length>0)
    {
        sqlText = [string stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"[" withString:@"/["];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"]" withString:@"/]"];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"%" withString:@"/%"];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"&" withString:@"/&"];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"_" withString:@"/_"];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@"(" withString:@"/("];
        sqlText = [sqlText stringByReplacingOccurrencesOfString:@")" withString:@"/)"];
    }
    return sqlText;
}</span>
           

插入後直接取出即可。