我正在使用Java应用程序来读取文本文件,并将它们输出到SQL脚本,最终输出到Mysql数据库。其中一列由几行未格式化的文本组成,包括逗号和撇号等符号。让事情变得更困难的是,我故意添加了新行,以保持文本的可读性。有没有办法让MySQL忽略会导致问题的字符组合(主要是撇号,但我有办法知道这些文本块将包含什么)而不中断换行符?
发布于 2012-06-14 04:40:48
请通读: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\%注意:我对\Z的实现不是很确定,也许有人可以详细说明一下。
发布于 2012-01-06 08:44:48
您必须最初添加转义斜杠:\ So like \‘表示这是一个实际的单引号。在放入内容时,您可以使用PHP来add_slash()您要放入数据库的字符串,自动为您转义它们。
发布于 2012-06-14 04:59:21
我知道您想输出一个SQL脚本,但总的来说,我认为直接访问数据库并让驱动程序为您转义文本要好得多。
SQL:更新myTable set value1=?value2=在哪里?
然后在代码中创建一个PreparedStatement并调用setParameter(1,value1)等。
驱动程序将负责转义撇号和其他特殊字符。
https://stackoverflow.com/questions/8751891
复制相似问题