2012-01-06 365 views
2

我正在使用Java應用程序讀取文本文件並將它們輸出到SQL腳本並最終輸出到Mysql數據庫。其中一列由幾行未格式化的文本組成,包括逗號和撇號等符號。爲了讓事情更加困難,我有意添加新行以保持文本的可讀性。有沒有辦法讓MySQL忽略會導致問題的字符組合(主要是撇號,但我知道這些文本塊將包含哪些內容),而不會破壞換行符?如何自動轉義mysql文本塊中的字符

回答

0

通讀此:http://dev.mysql.com/doc/refman/5.1/en/string-literals.html

概括地說,這些都是字符替換

\0 An ASCII NUL (0x00) character. 
\' A single quote (「'」) character. 
\" A double quote (「"」) character. 
\b A backspace character. 
\n A newline (linefeed) character. 
\r A carriage return character. 
\t A tab character. 
\Z ASCII 26 (Control+Z). See note following the table. 
\\ A backslash (「\」) character. 
\% A 「%」 character. See note following the table. 
\_ A 「_」 character. See note following the table. 

這是我一直使用的是什麼在某些Java程序時,我不能/不要使用參數綁定。

public static String addSlashesSearchMode(String s) { 
    return addSlashes(s, true); 
} 

public static String addSlashes(String s) { 
    return addSlashes(s, false); 
} 

private static String addSlashes(String s, boolean search) { 
    if (s == null) { 
     return s; 
    } 
    String[][] chars; 
    if(!search) { 
     chars = new String[][ ]{ 
       {"\\", "\\\\"}, 
       {"\0", "\\0"}, 
       {"'", "\\'"}, 
       {"\"", "\\\""}, 
       {"\b", "\\b"}, 
       {"\n", "\\n"}, 
       {"\r", "\\r"}, 
       {"\t", "\\t"}, 
       {"\\Z", "\\\\Z"}, // not sure about this one 
       {"%", "\\%"},  // used in searching 
       {"_", "\\_"} 
     }; 
    } else { 
     chars = new String[][ ]{ 
       {"\\", "\\\\"}, 
       {"\0", "\\0"}, 
       {"'", "\\'"}, 
       {"\"", "\\\""}, 
       {"\b", "\\b"}, 
       {"\n", "\\n"}, 
       {"\r", "\\r"}, 
       {"\t", "\\t"}, 
       {"\\Z", "\\\\Z"}, // not sure about this one 
     }; 
    } 
    for (String[] c : chars) { 
     s = s.replace(c[0], c[1]); 
    } 
    return s; 
} 

使用StringUtils.addSlashes("ke\rn\tny's\"\nnew li\\ne%"))

輸出ke\rn\tny\'s\"\nnew li\\ne\%

輸出看在phpMyAdmin

ke 
n ny's" 
new li\ne\% 

注意:我真的不知道AB執行\Z,也許有人可以詳細說明。

1

您將不得不最初添加轉義斜槓:\ 所以像\'意味着它的實際單引號。將東西放入時,可以使用PHP將add_slash()字符串放入數據庫中,並自動爲您轉義它們。

0

我知道你想輸出一個SQL腳本,但總的來說,我認爲直接訪問數據庫並讓驅動程序爲你轉義文本要好得多。

SQL:update myTable set value1 =?其中value2 =?

然後在代碼中創建一個PreparedStatement和調用的setParameter(1,值1)等

司機將照顧逃脫撇號和其它特殊字符。