如何在JDBI中动态绑定表名

Hel*_*oPe 9 java mysql sql database jdbi

我试过用

SELECT COUNT(*) FROM :TableName;
Run Code Online (Sandbox Code Playgroud)

在我使用的JDBI中

.bind("Tablename", "MyTable")
Run Code Online (Sandbox Code Playgroud)

结果总是在单引号内:

SELECT COUNT(*) FROM 'MyTable';
Run Code Online (Sandbox Code Playgroud)

是否有适当的方法来参数化TableName

Rav*_*ddy 13

bind不是用于标识符,而是用于值.Table是一个数据库对象,它的名称是引用它的标识符.

因此,您必须显式构造sql查询字符串以动态包含表名.

示例:

String tableName = "employee";
String sql = "SELECT COUNT(*) FROM " + tableName;
Run Code Online (Sandbox Code Playgroud)

然后,如果要根据字段值或表达式过滤计数或任何其他结果,则可以对其进行绑定.

示例:

sql = sql + " WHERE deptno = :deptNoToBind";
int deptNo = 20;
// ... use db handle to bind
handle.createQuery( sql )
      .bind( "deptNoToBind", deptNo );
Run Code Online (Sandbox Code Playgroud)

您可以看到列或表达式的值是绑定的,但不是标识符.

您正在寻找的功能是@Define - 以下是它的用法示例:

import org.skife.jdbi.v2.sqlobject.customizers.Define;
...
@SqlUpdate("create table if not exists <table> (" +
        "startTime TimeStamp not null," +
        "stopTime TimeStamp not null," +
        "uuid varchar(255)" +
        ")")
public void createTable(@Define("table") String table);
Run Code Online (Sandbox Code Playgroud)

  • **@ UnknownDownVoter**:投票失败的具体原因! (4认同)
  • 如果对<table>使用<*>语法,则需要使用@ UseStringTemplate3StatementLocator注释接口,并且对于此注释,将此依赖项添加到pom <dependency> <groupId> org.antlr </ groupId> <artifactId> stringtemplate </ artifactId > <version> 3.2 </ version> </ dependency> (2认同)

Can*_*kçu 5

import org.skife.jdbi.v2.sqlobject.customizers.Define;
import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator;

@UseStringTemplate3StatementLocator
public interface CreateTableDAO {

    @SqlUpdate("create table if not exists <table> (" +
        "startTime TimeStamp not null," +
        "stopTime TimeStamp not null," +
        "uuid varchar(255)" +
        ")")
    public void createTable(@Define("table") String table);

}
Run Code Online (Sandbox Code Playgroud)

不要忘记为UseStringTemplate3StatementLocator注释添加依赖项

<dependency>
    <groupId>org.antlr</groupId>
    <artifactId>stringtemplate</artifactId>
    <version>3.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)