如何在准备好的语句中设置列表

时间:2014-03-02 10:53:28

标签: java prepared-statement

如何在预准备语句中设置列表( statement.setString(1,productCode); )。 请参阅下面的代码段。

由于

public static List<Message> listAllWonBids(List<Message> productCode,
    Connection connection) {

    List<Message> winners = new ArrayList<Message>();

    String sql = "SELECT b.`id`, b.`msisdn` as msisdn ,b.`productname` as productname, b.`productcode` as productcode, max(b.`amount`) as amount FROM  "
        + TableNames.SAVEDBIDSTABLE
        + " b where productcode = ? "
        + " group by amount order by productcode, amount  desc limit 1";

    PreparedStatement statement = null;
    ResultSet resultSet = null;

    try {
        LOGGER.info(sql);

        if (connection == null || connection.isClosed())
            connection = DBConnection.getConnection();

        statement = connection.prepareStatement(sql);

        **statement.setString(1, productCode);** 

        resultSet = statement.executeQuery();

注意:productCode来自下面显示的另一个列表

public static List<Message> allProductCode(Connection connection) {
    List<Message> productcodes = new ArrayList<Message>();

    PreparedStatement statement = null;
    ResultSet resultSet = null;

    String sql = "SELECT `productCode` FROM " + TableNames.AUCTIONTABLE1
        + " WHERE date(`endDate`) = curdate() order by `id` desc";

2 个答案:

答案 0 :(得分:2)

这是不可能的,要么使用IN

以编程方式生成where子句
"where productcode in (" + listToStringEncoding + ")"

或者循环遍历列表并多次调用该语句。

其他可能性是加入2个陈述......

答案 1 :(得分:1)

您可以合并这两个查询。类似的东西:

String sql = "SELECT b.`id`, b.`msisdn` as msisdn ,b.`productname` as productname, b.`productcode` as productcode, max(b.`amount`) as amount FROM  " 
+ TableNames.SAVEDBIDSTABLE + " b where productcode in (SELECT `productCode` FROM " 
+ TableNames.AUCTIONTABLE1 + " WHERE date(`endDate`) = curdate() order by `id` desc) group by amount order by productcode, amount  desc limit 1";

然后你不需要任何参数