将数据库中的user表中的数据,封装在User对象中
代码:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建用户集合
List<User> userList=new ArrayList<User>();
//创建用户对象
User user=new User();
//创建JDBC连接对象
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai",
"root","123456");
//获取预编译数据库操作对象
String sql="select username,email,userpwd from t_userinfo";
preparedStatement=connection.prepareStatement(sql);
//执行Sql语句
resultSet=preparedStatement.executeQuery();
//处理查询结果集
while(resultSet.next()){
//将在数据库中查询到的信息,封装在实例类中
user=new User();
user.setUserName(resultSet.getString("username"));
user.setUserEmail(resultSet.getString("email"));
user.setUserPwd(resultSet.getString("userpwd"));
//将每一个用户对象添加到集合中
userList.add(user);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//遍历集合,输出用户信息
if(userList!=null){
Iterator iterator=userList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
}
}
原文:https://www.cnblogs.com/szqengr/p/14698426.html