Java软件开发基础知识梳理之(2)------动态创建PreparedStatement解决SQL中带的in条件

来源:互联网 发布:飞天怎么样知乎 编辑:程序博客网 时间:2024/05/20 07:35

示例代码如下所示,虽然可以解决PreparedStatement的SQL语句中带in 条件的问题,但无法享受PreparedStatement的缓存带来的好处

package com.justin.pk4;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.util.Set;import javax.xml.crypto.Data;public class DynamicPreparedStatement {public static String preparePlaceHolderStr(int length) {StringBuilder builder = new StringBuilder();for (int i = 0; i < length;) {builder.append("?");if (++i < length) {builder.append(",");}}return builder.toString();}public static void setValueForPlaceHolder(PreparedStatement preparedStatement, Object... values) throws SQLException {for (int i = 0; i < values.length; i++) {preparedStatement.setObject(i + 1, values[i]);}}public List<Data> find(Set<Long> ids) throws SQLException {String SQL_FIND = "SELECT id, name, sex FROM t_student WHERE id IN (%s)";    Connection connection = null;    PreparedStatement statement = null;    ResultSet resultSet = null;    List<Data> list = new ArrayList<Data>();    String sql = String.format(SQL_FIND, preparePlaceHolderStr(ids.size()));    try{        connection = getConnection();        statement = connection.prepareStatement(sql);        setValueForPlaceHolder(statement, ids.toArray());        resultSet = statement.executeQuery();        while (resultSet.next()) {            //TODO        }    } finally {        //TODO  close connection    }    return list;}private Connection getConnection(){ Connection connection = null; //TODO return connection;}}


 

0 0