1.新建一个对象,里面的元素包含需要存储的数据
package com.wzq.list.users;
/**
* 用户基本信息
* @author wangzhiqiang 2016-11-01
*
*/
public class UserInfo {
/**
* 用户ID
*/
private Integer uid;
/**
* 用户名
*/
private String userName;
/**
* 密码
*/
private String pswd;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPswd() {
return pswd;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
2.查询数据库,把取得的数据存储于List表单中
package com.wzq.list.users;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
* 用户服务工具类
* @author wangzhiqiang 2016-11-01
*
*/
public class UserService {
/**
* 根据用户名查找用户
* @param userName
*/
public ArrayList getUserList(String userName){
//加载MySql的驱动类
try {
Class.forName("com.mysql.jdbc.Driver") ;
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
Connection con = null;
Statement stmt = null ;
ResultSet rs = null;//结果集
String url = "jdbc:mysql://221.236.172.90:3306/shuyue" ;
String username = "shuyue" ;
String password = "asd123" ;
try{
con = DriverManager.getConnection(url , username , password ) ;
stmt = con.createStatement() ;
String sql = "select id,user_name,pass_word from user_info where user_name like '%"+userName+"%'";
rs = stmt.executeQuery(sql) ;
ArrayList list = new ArrayList();
while(rs.next()){
String name = rs.getString("user_name") ;
String pswd = rs.getString("pass_word") ;
int id = rs.getInt("id") ;
UserInfo user = new UserInfo();
user.setUid(id);
user.setUserName(name);
user.setPswd(pswd);
list.add(user);
}
return list;
}catch(SQLException se){
System.out.println("数据库连接失败!");
se.printStackTrace() ;
} finally{
if (rs != null) { // 关闭记录集
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) { // 关闭声明
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) { // 关闭连接对象
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return new ArrayList();
}
}
3.提取数据
package com.wzq.list.users;
import java.util.ArrayList;
public class ServletTest {
public static void main(String[] args) {
//设计现在是在servlet的get或post方法中
String userName = "m";//从前端提交过来的参数
UserService us = new UserService();//新建UserService对象
ArrayList l = us.getUserList(userName);//新建ArrayList对象,并赋值给l
/*for(int i=0;i<10;i++){
System.out.println(i);
}*/
int length = l.size();
String h = "<html><body>";
for(int i=0;i<length;i++){
UserInfo u = (UserInfo)l.get(i); //新建UserInfo对象,并把ArrayList对象中的值赋给他
System.out.println(u.getUserName());
}
h = h+"</body></html>";
}
}