如何在准备好的语句上设置参数列表?

发布于 2024-08-02 13:50:30 字数 380 浏览 6 评论 0原文

我有一个姓名列表,例如:

List<String> names = ...
names.add('charles');
...

和一个声明:

PreparedStatement stmt = 
  conn.prepareStatement('select * from person where name in ( ? )');

如何执行以下操作:

stmt.setParameterList(1,names);

有解决方法吗?有人可以解释为什么缺少这个方法吗?

使用:java、postgresql、jdbc3

i have a list of names e.g.:

List<String> names = ...
names.add('charles');
...

and a statement:

PreparedStatement stmt = 
  conn.prepareStatement('select * from person where name in ( ? )');

how to do the following:

stmt.setParameterList(1,names);

Is there a workaround? can someone explain why this method is missing?

using: java, postgresql, jdbc3

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

绝不服输 2024-08-09 13:50:30

这个问题很老了,但没有人建议使用 setArray

这个答案可能会有所帮助https://stackoverflow.com/a/10240302 /573057

This question is very old, but nobody has suggested using setArray

This answer might help https://stackoverflow.com/a/10240302/573057

青柠芒果 2024-08-09 13:50:30

据我所知,没有简单的方法通过在 PreparedStatement 上设置一个列表来做到这一点。

编写带有适当数量的问号(与列表中的数量相同)的 SQL 语句(或者更好地替换单个 ? 或类似标记)的代码,然后迭代列表,为每个问号设置参数。

There's no clean way to do this simply by setting a list on the PreparedStatement that I know of.

Write code that constructs the SQL statement (or better replaces a single ? or similar token) with the appropriate number of questions marks (the same number as in your list) and then iterate over your list setting the parameter for each.

浅沫记忆 2024-08-09 13:50:30

由于类型擦除列表的参数类型在运行时丢失,因此缺少此方法。因此需要添加几个方法:setIntParameterssetLongParameterssetObjectParameters

this method is missing due to type erasure the parameter type of the List is lost at runtime. Therefore the need to add several methods arires: setIntParameters, setLongParameters, setObjectParameters, etc

软糖 2024-08-09 13:50:30

对于 postgres 9 我使用了这种方法:

 jdbcTemplate.query(getEmployeeReport(), new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setTimestamp(1, new java.sql.Timestamp(from.getTime()));
            ps.setTimestamp(2, new java.sql.Timestamp(to.getTime()));
            StringBuilder ids = new StringBuilder();
            for (int i = 0; i < branchIds.length; i++) {
                ids.append(branchIds[i]);
                if (i < branchIds.length - 1) {
                    ids.append(",");
                }
            }
            // third param is inside IN clause
            // Use Types.OTHER avoid type check while executing query  
            ps.setObject(3, ids.toString(), **Types.OTHER**);
        }
    }, new PersonalReportMapper());

For postgres 9 I have used this approach:

 jdbcTemplate.query(getEmployeeReport(), new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            ps.setTimestamp(1, new java.sql.Timestamp(from.getTime()));
            ps.setTimestamp(2, new java.sql.Timestamp(to.getTime()));
            StringBuilder ids = new StringBuilder();
            for (int i = 0; i < branchIds.length; i++) {
                ids.append(branchIds[i]);
                if (i < branchIds.length - 1) {
                    ids.append(",");
                }
            }
            // third param is inside IN clause
            // Use Types.OTHER avoid type check while executing query  
            ps.setObject(3, ids.toString(), **Types.OTHER**);
        }
    }, new PersonalReportMapper());
伴梦长久 2024-08-09 13:50:30

如果问题的含义是在一次调用中设置多个参数...

因为类型验证已经在更高级别中定义,所以我认为唯一需要的是 setObject(...)

因此,可以使用实用方法:

public static void addParams(PreparedStatement preparedStatement, Object... params) throws SQLException {
    for (int i = 0; i < params.length; i++) {
        Object param = params[i];
        preparedStatement.setObject(i+1, param);
    }
}

用法:

SqlUtils.addParams(preparedStatement, 1, '2', 3d);

随意将其转换为 Java 8 lambda :)

In case the questions' meaning is to set several params in a single call...

Because the type validation is already defined in a higher level, I think the only need is for setObject(...).

Thus, a utility method can be used:

public static void addParams(PreparedStatement preparedStatement, Object... params) throws SQLException {
    for (int i = 0; i < params.length; i++) {
        Object param = params[i];
        preparedStatement.setObject(i+1, param);
    }
}

Usage:

SqlUtils.addParams(preparedStatement, 1, '2', 3d);

Feel free converting this to a Java 8 lambda :)

失与倦" 2024-08-09 13:50:30

今天早上我正在审查代码,我的一位同事采用了不同的方法,只需使用 setString("name1','name2','name3") 传递参数即可。

注意:我跳过了开头和结尾的单引号,因为这些将由 setString 添加。

I was reviewing code this morning and one of my colleagues had a different approach, just pass the parameter using setString("name1','name2','name3").

Note: I skipped the single quote at the beginning and end because these are going to be added by the setString.

七月上 2024-08-09 13:50:30

在检查了不同论坛中的各种解决方案并且没有找到好的解决方案之后,我觉得我想出的以下黑客是最容易遵循和编码的。但请注意,这不使用准备好的查询,但无论如何都会完成工作:

示例:假设您有一个要在“IN”子句中传递的参数列表。只需在“IN”子句中放置一个虚拟字符串,例如“PARAM”确实表示将代替该虚拟字符串的参数列表。

    select * from TABLE_A where ATTR IN (PARAM);

您可以将所有参数收集到 Java 代码中的单个字符串变量中。这可以按如下方式完成:

    String param1 = "X";
    String param2 = "Y";
    String param1 = param1.append(",").append(param2);

您可以将所有用逗号分隔的参数附加到单个字符串变量“param1”中,在我们的例子中。

将所有参数收集到单个字符串中后,您可以将查询中的虚拟文本(即本例中的“PARAM”)替换为参数字符串(即 param1)。以下是您需要执行的操作:

    String query = query.replaceFirst("PARAM",param1); where we have the value of query as 

    query = "select * from TABLE_A where ATTR IN (PARAM)";

您现在可以使用executeQuery() 方法执行查询。只需确保您的查询中任何地方都没有“PARAM”一词。您可以使用特殊字符和字母的组合来代替单词“PARAM”,以确保查询中不可能出现此类单词。希望你能找到解决方案。

After examining various solutions in different forums and not finding a good solution, I feel the below hack I came up with, is the easiest to follow and code. Note however that this doesn't use prepared query but gets the work done anyway:

Example: Suppose you have a list of parameters to pass in the 'IN' clause. Just put a dummy String inside the 'IN' clause, say, "PARAM" do denote the list of parameters that will be coming in the place of this dummy String.

    select * from TABLE_A where ATTR IN (PARAM);

You can collect all the parameters into a single String variable in your Java code. This can be done as follows:

    String param1 = "X";
    String param2 = "Y";
    String param1 = param1.append(",").append(param2);

You can append all your parameters separated by commas into a single String variable, 'param1', in our case.

After collecting all the parameters into a single String you can just replace the dummy text in your query, i.e., "PARAM" in this case, with the parameter String, i.e., param1. Here is what you need to do:

    String query = query.replaceFirst("PARAM",param1); where we have the value of query as 

    query = "select * from TABLE_A where ATTR IN (PARAM)";

You can now execute your query using the executeQuery() method. Just make sure that you don't have the word "PARAM" in your query anywhere. You can use a combination of special characters and alphabets instead of the word "PARAM" in order to make sure that there is no possibility of such a word coming in the query. Hope you got the solution.

梦里°也失望 2024-08-09 13:50:30

其他方法:

public void setValues(PreparedStatement ps) throws SQLException {
    // first param inside IN clause with myList values
    ps.setObject(1 , myList.toArray(), 2003); // 2003=array in java.sql.Types
}

Other method :

public void setValues(PreparedStatement ps) throws SQLException {
    // first param inside IN clause with myList values
    ps.setObject(1 , myList.toArray(), 2003); // 2003=array in java.sql.Types
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文