日期:2014-05-17 浏览次数:20812 次
public List<User> getAllUsers(){按条件查询:
//下面三行要抽离封装一下的,这里演示就不搞复杂了
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysqldb1";
Connection conn = DriverManager.getConnection(url, "root", "root");
Statement st = conn.createStatement();
String sql = "select * from user where 1=1";
ResultSet rs = st.executeQuery(sql);
List<User> users = new ArrayList<User>();
User user = null;
while (rs.next()) {
user = new User();
user.setId(rs.getString("id"));
user.setName("zhangsan");
users.add(user);
}
return users;
}
public List<User> getAllUsersByName(String name){你对比一下区别就明白了,就是条件的不同,按条件的话,将搜索框的条件作为形参传入方法中
//下面三行要抽离封装一下的,这里演示就不搞复杂了
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mysqldb1";
Connection conn = DriverManager.getConnection(url, "root", "root");
Statement st = conn.createStatement();
String sql = "select * from user where name = ?";
PreparedStatement pre = conn.prepareStatement(sql);
pre.setString(1, name);
ResultSet rs = pre.executeQuery();
List<User> users = new ArrayList<User>();
User user = null;
while (rs.next()) {
user = new User();
user.setId(rs.getString("id"));
user.setName(name);
users.add(user);
}
return users;
}