JDBC中的命名参数

Fak*_*een 68 java jdbc named-parameters

是否有一个名为JDBC中,而不是那些位置参数,比如@name,@city在下面的ADO.NET查询?

select * from customers where name=@name and city = @city
Run Code Online (Sandbox Code Playgroud)

Mal*_*lax 68

JDBC不支持命名参数.除非你一定要使用普通的JDBC(这会导致痛苦,让我告诉你),我建议使用Springs Excellent JDBCTemplate,它可以在没有整个IoC容器的情况下使用.

NamedParameterJDBCTemplate支持命名参数,您可以像这样使用它们:

 NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

 MapSqlParameterSource paramSource = new MapSqlParameterSource();
 paramSource.addValue("name", name);
 paramSource.addValue("city", city);
 jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
Run Code Online (Sandbox Code Playgroud)

  • 但是你必须在你的项目中包含许多Spring JAR,只是为了使用一些与NamedParameterJdbcTemplate相关的类.org.springframework.jdbc.jar不能单独使用,这很糟糕. (10认同)
  • `spring-jdbc`模块依赖于`spring-core`,`spring-framework`和`spring-tx`.`NamedParameterJdbcTemplate`需要一些重写才能使用独立.https://repo1.maven.org/maven2/org/springframework/spring-jdbc/4.3.8.RELEASE/spring-jdbc-4.3.8.RELEASE.pom (4认同)
  • 解压缩jar文件 - 并将所需的类文件复制到项目中.瞧.. (3认同)
  • @Malax正在制作的一点是你可以使用spring standalone的NamedParameterJdbcTemplate.您不必更改代码库的任何其他部分. (2认同)

Inv*_*oft 28

为了避免包含大型框架,我认为一个简单的自制类可以做到这一点.

处理命名参数的类示例:

public class NamedParamStatement {
    public NamedParamStatement(Connection conn, String sql) throws SQLException {
        int pos;
        while((pos = sql.indexOf(":")) != -1) {
            int end = sql.substring(pos).indexOf(" ");
            if (end == -1)
                end = sql.length();
            else
                end += pos;
            fields.add(sql.substring(pos+1,end));
            sql = sql.substring(0, pos) + "?" + sql.substring(end);
        }       
        prepStmt = conn.prepareStatement(sql);
    }

    public PreparedStatement getPreparedStatement() {
        return prepStmt;
    }
    public ResultSet executeQuery() throws SQLException {
        return prepStmt.executeQuery();
    }
    public void close() throws SQLException {
        prepStmt.close();
    }

    public void setInt(String name, int value) throws SQLException {        
        prepStmt.setInt(getIndex(name), value);
    }

    private int getIndex(String name) {
        return fields.indexOf(name)+1;
    }
    private PreparedStatement prepStmt;
    private List<String> fields = new ArrayList<String>();
}
Run Code Online (Sandbox Code Playgroud)

调用类的示例:

String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();
Run Code Online (Sandbox Code Playgroud)

请注意,上面的简单示例不会处理两次使用命名参数.它也不处理使用:引号内的符号.

  • 我用你的做了一些小的修改。` Pattern findParametersPattern = Pattern.compile("(?&lt;!')(:[\\w]*)(?!')"); 匹配器 matcher = findParametersPattern.matcher(statementWithNames); while (matcher.find()) { fields.add(matcher.group().substring(1)); } prepStmt = conn.prepareStatement(statementWithNames.replaceAll(findParametersPattern.pattern(), "?")); (3认同)
  • @WillieT 代码的要点 https://gist.github.com/ruse​​el/e10bd3fee3c2b165044317f5378c7446 (3认同)
  • 我还建议添加“implements AutoClosable”(需要 java7+) (2认同)

ska*_*man 23

Vanilla JDBC仅支持CallableStatement(例如setString("name", name))中的命名参数,即便如此,我怀疑底层存储过程实现必须支持它.

如何使用命名参数的示例:

//uss Sybase ASE sysobjects table...adjust for your RDBMS
stmt = conn.prepareCall("create procedure p1 (@id int = null, @name varchar(255) = null) as begin "
        + "if @id is not null "
        + "select * from sysobjects where id = @id "
        + "else if @name is not null "
        + "select * from sysobjects where name = @name "
        + " end");
stmt.execute();

//call the proc using one of the 2 optional params
stmt = conn.prepareCall("{call p1 ?}");
stmt.setInt("@id", 10);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
    System.out.println(rs.getString(1));
}


//use the other optional param
stmt = conn.prepareCall("{call p1 ?}");
stmt.setString("@name", "sysprocedures");
rs = stmt.executeQuery();
while (rs.next())
{
    System.out.println(rs.getString(1));
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,它是正确的,但并非所有db都支持此功能.我在postgresql上测试它不起作用. (4认同)
  • 是的,显然数据库必须首先支持命名参数......而 postgres 似乎不支持。这个问题暗示他们的数据库确实支持这一点,并且想要了解如何在 JDBC 中使用该功能。 (2认同)