PreparedStatement,分页查询
package com.javakc.test2;
import com.javakc.db.Utils;
import com.javakc.vo.Card;
import com.javakc.vo.Condition;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class testQueryLimit {
public static List<Card> queryLimit(Condition condition, int offset, int rows) throws SQLException {
List<Card> list = new ArrayList<>();
Connection connection = null;
try {
connection = Utils.getConnection();
String sql = "select id,name,sex,credit from card where 1=1 ";
List<Object> paramList = new ArrayList<>();
if (condition != null) {
if (condition.getName() != null && condition.getName().trim().length() > 0) {
sql += "and name like ? ";
paramList.add("%" + condition.getName() + "%");
}
if (condition.getSex() != null && condition.getSex().trim().length() > 0) {
sql += "and sex=?";
paramList.add(condition.getSex());
}
if (condition.getCredit1() != null) {
sql += "and credit >=? ";
paramList.add(condition.getCredit1());
}
if (condition.getCredit2() != null) {
sql += "and credit<=? ";
paramList.add(condition.getCredit2());
}
}
sql += "limit ?,?";
paramList.add(offset);
paramList.add(rows);
System.out.println(sql);
System.out.println(paramList);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < paramList.size(); i++) {
preparedStatement.setObject(i + 1, paramList.get(i));
}
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String sex = resultSet.getString("sex");
int credit = resultSet.getInt("credit");
Card c = new Card();
c.setId(id);
c.setName(name);
c.setSex(sex);
c.setCredit(credit);
list.add(c);
}
preparedStatement.close();
resultSet.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return list;
}
public static void main(String[] args) throws SQLException {
Condition condition = new Condition();
condition.setName("a");
condition.setSex("男");
condition.setCredit1(1);
condition.setCredit2(5);
List<Card> list = queryLimit(condition, 0, 3);
for (Card card : list) {
System.out.println(card);
}
}
}