首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何自动转义mysql文本块中的字符

问如何自动转义mysql文本块中的字符
EN

Stack Overflow用户
提问于 2012-01-06 08:26:30
回答 3查看 2.9K关注 0票数 2

我正在使用Java应用程序来读取文本文件,并将它们输出到SQL脚本,最终输出到Mysql数据库。其中一列由几行未格式化的文本组成,包括逗号和撇号等符号。让事情变得更困难的是,我故意添加了新行,以保持文本的可读性。有没有办法让MySQL忽略会导致问题的字符组合(主要是撇号,但我有办法知道这些文本块将包含什么)而不中断换行符?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-06-14 04:40:48

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

简而言之,这些是要替换的字符

代码语言:javascript
复制
\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程序中已经使用了一段时间的方法。

代码语言:javascript
复制
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中查看输出

代码语言:javascript
复制
ke
n    ny's"
new li\ne\%

注意:我对\Z的实现不是很确定,也许有人可以详细说明一下。

票数 0
EN

Stack Overflow用户

发布于 2012-01-06 08:44:48

您必须最初添加转义斜杠:\ So like \‘表示这是一个实际的单引号。在放入内容时,您可以使用PHP来add_slash()您要放入数据库的字符串,自动为您转义它们。

票数 1
EN

Stack Overflow用户

发布于 2012-06-14 04:59:21

我知道您想输出一个SQL脚本,但总的来说,我认为直接访问数据库并让驱动程序为您转义文本要好得多。

SQL:更新myTable set value1=?value2=在哪里?

然后在代码中创建一个PreparedStatement并调用setParameter(1,value1)等。

驱动程序将负责转义撇号和其他特殊字符。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8751891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档