繁体   English   中英

使用jooq创建查询字符串时如何转义单引号?

[英]How to escape single quotes while creating a query string with jooq?

我正在尝试通过以下方式创建一个 jooq 查询字符串

DSL.using(SQLDialect.MYSQL)
            .select(
                    ImmutableList.of(DSL.field("Name"))
            .from(DSL.table("Account"))
            .where(DSL.field("Name").eq("Yaswanth's Company"))).toString()

结果查询字符串将单引号转义为另一个单引号,这是转义单引号的默认 mySQL 方式。

"select Name from Account where Name = 'Yaswanth''s Company'"

但是我需要用反斜杠转义单引号,因为我正在为 salesforce 形成查询字符串。 (称为 SOQL)。

我需要这样的查询字符串

"select Name from Account where Name = 'Yaswanth\\'s Company'"

我查看了 jooq 库代码,这是在 DefaultBinding 类中硬编码的

private final String escape(Object val, Context<?> context) {
    String result = val.toString();

    if (needsBackslashEscaping(context.configuration()))
        result = result.replace("\\", "\\\\");

    return result.replace("'", "''");
}

我有没有办法通过 DSL.using(*, *) 传递的配置或设置来覆盖这个默认行为?

大多数 SQL 数据库都遵循将单引号加倍以进行转义的 SQL 标准,但使此功能可配置当然是有意义的。 我们可能会使用#5873为 jOOQ 3.10 执行此操作。

同时,最好的解决方法是为所有 String 类型编写自己的数据类型绑定,并在生成 SQL 字符串时覆盖DefaultBinding行为。 类似的东西:

代码生成配置

使用<forcedTypes/>

<forcedType>
    <userType>java.lang.String</userType>
    <binding>com.example.AlternativeEscapingStringBinding</binding>
    <!-- add other vendor-specific string type names here -->
    <types>(?i:N?(VAR)?CHAR|TEXT|N?CLOB)</types>
</forcedType>

数据类型绑定

public class AlternativeEscapingStringBinding implements Binding<String, String> {
    ...

    @Override
    public void sql(BindingSQLContext<String> ctx) throws SQLException {
        if (ctx.paramType() == ParamType.INLINED) 
            if (ctx.value() == null)
                ctx.render().sql('null');
            else
                ctx.render()
                   .sql('\'')
                   .sql(ctx.value().replace("'", "\\'"))
                   .sql('\'');
        else
            ctx.render().sql('?');
    }
}

如果您没有使用代码生成器

您仍然可以手动将您自己的数据类型绑定应用到您的字段,如下所示:

DSL.field("Name", SQLDataType.VARCHAR
                             .asConvertedDataType(new AlternativeEscapingStringBinding()));

你只需要每次都记住这一点......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM