JDBC方式从数据库中查询数据并显示

时间:2023-01-28 14:55:16

新博客地址https://www.jianshu.com/u/8e54644eafae

1.创建数据库表myuser

DROP TABLE IF EXISTS `myuser`;
CREATE TABLE `myuser` (
`user_name` varchar(255) NOT NULL COMMENT '姓名',
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

2.实体类

package yang.mybatis.domain;

public class User {
  //实体类的成员变量和数据库表的字段名称和类型一致
private int id;
private String user_name;
private int age;
private String password; public User(){}
public User(String name,int id, int age,String password) {
super();
this.id = id;
this.user_name = name;
this.age = age;
this.password = password;
}
  //创建每个成员变量的set和get方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String name) {
this.user_name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setPassword(String password) {
this.password = password;
} public String getPassword() {
return password;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + user_name + ", age=" + age + "]";
} }

3.1UserDao,连接数据库,查询数据库表中所有的记录

package yang.mybatis.dao;

import yang.mybatis.domain.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List; /**
* Created by yangshijing on 2017/11/10 0010.
*/
public class UserDaoTest {
public List<User> getAll(){
    
List<User> Users = new ArrayList<User>(); Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; try {
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql:///mydb";
String user = "root";
String pass= "1234"; Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, pass); String sql = "SELECT user_name, id, age, password FROM myuser";
preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
String user_name = resultSet.getString(1);
int id = resultSet.getInt(2);
int age = resultSet.getInt(3);
String password = resultSet.getString(4);
User userl= new User(user_name,id,age,password);
Users.add(userl);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(resultSet != null){
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if(preparedStatement != null){
preparedStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} return Users;
}
}

3.2根据用户Id删除用户数据

   public void deleteById(int id) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql:///mydb";
String user = "root";
String pass= "1234"; Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, pass); String sql = "DELETE FROM myuser WHERE id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,id);
int i = preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(preparedStatement != null){
preparedStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

4.1编写查询Servlet

package yang.mybatis.servlet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import yang.mybatis.dao.UserDaoImp;
import yang.mybatis.dao.UserDaoTest;
import yang.mybatis.domain.User; import java.io.IOException;
import java.util.List; /**
* Created by yangshijing on 2017/11/10 0010.
*/
@Controller
public class ListAllStudent extends javax.servlet.http.HttpServlet {
@Override
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
} @Override
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
try {
UserDaoTest userDaoTest = new UserDaoTest();
List<User> list = userDaoTest.getAll();
//将从数据库中查询到的数据方法request域中
request.setAttribute("list",list);
//利用请求转发的方式,将这次请求域中的数据传到另一个页面进行显示
    request.getRequestDispatcher("/jsp/hello1.jsp").forward(request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

4.2删除Servlet

package yang.mybatis.servlet;

import yang.mybatis.dao.UserDaoTest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* Created by yangshijing on 2017/11/10 0010.
*/
public class DeleteServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
} @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     //从request域中获取的数据是String类型
String id = request.getParameter("id");
UserDaoTest userDaoTest = new UserDaoTest();
     //通过Interger.parseInt()方法,将String类型转换为int类型
userDaoTest.deleteById(Integer.parseInt(id));
request.getRequestDispatcher("/listAllStudent").forward(request,response);
}
}

5.Web应用根目录下/jsp/hello1.jsp页面对数据进行显示

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<a href="/myAction/listAllStudent.action">SpringMvc</a>
<a href="/listAllStudent">Servlet</a>
<br>
  <!--设置表格边框的宽度-->
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>密码</th>
<th>删除</th>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td> ${user.id}</td>
<td> ${user.user_name}</td>
<td> ${user.age}</td>
<td> ${user.password}</td>
<td><a href="/deleteServlet?id=${user.id}">Delete</a></td>
</tr>
</c:forEach>
</table> </body>
</html>

6.结果

JDBC方式从数据库中查询数据并显示