JDBC1

文章描述了一个使用Java编写的StuDAO类,用于操作数据库(如MySQL)的CRUD操作,以及与之关联的Servlet(如QueryAllServlet)和JSTL在Web页面展示数据。内容涉及数据库连接管理、SQL查询和参数化语句执行。
摘要由CSDN通过智能技术生成

StuDAO

package com.hbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.hbc.bean.DBUtil;
import com.hbc.bean.StuBean;

public class StuDAO {

    public StuDAO() {
        // TODO Auto-generated constructor stub
    }
    
    public List queryAll() {
        List list = new ArrayList();
        Connection conn = DBUtil.getConnection();
        Statement stat = DBUtil.getStatement(conn);    
        ResultSet rs = null;
        try {
            rs = stat.executeQuery("select * from tb_stu");
            StuBean stu = null;
            while(rs.next()) {
                stu = new StuBean();
                stu.setStuId(rs.getInt(1)); 
                stu.setStuName(rs.getString(2));
                stu.setStuSex(rs.getString(3));
                stu.setStuPhone(rs.getString(4));
                list.add(stu);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(conn, stat, rs);
        }
        return list;
    }
    
    public void deleteById(int stuId) {
        List list = new ArrayList();
        Connection conn = DBUtil.getConnection();
        Statement stat = DBUtil.getStatement(conn);    
        try {
            int rn = stat.executeUpdate("delete from tb_stu where stuId="+stuId);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stat);
        }
    }
    
    public void addStu(StuBean stu) {
        Connection conn = DBUtil.getConnection();
        PreparedStatement stat = null;
        String sql = "insert into tb_stu(stuId,stuName,stuSex,stuPhone) values(?,?,?,?)";
        try {
            stat = conn.prepareStatement(sql);
            stat.setInt(1, stu.getStuId());
            stat.setString(2, stu.getStuName());
            stat.setString(3, stu.getStuSex());
            stat.setString(4, stu.getStuPhone());
            int rtn = stat.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stat);
        }
    }
    
    public StuBean selectById(int stuId) {
        StuBean stu = new StuBean();
        Connection conn = DBUtil.getConnection();
        Statement stat = DBUtil.getStatement(conn);    
        ResultSet rs = null;
        try {
            rs = stat.executeQuery("select * from tb_stu where stuId="+stuId);
            while(rs.next()) {
                stu.setStuId(rs.getInt(1)); 
                stu.setStuName(rs.getString(2));
                stu.setStuSex(rs.getString(3));
                stu.setStuPhone(rs.getString(4));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.closeAll(conn, stat,rs);
        }
        return stu;
    }
    
    
    public void updateStu(StuBean stu) {
        Connection conn = DBUtil.getConnection();
        PreparedStatement stat = null;
        String sql = "update tb_stu set stuName=?,stuSex=?,stuPhone=? where stuId=?";
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, stu.getStuName());
            stat.setString(2, stu.getStuSex());
            stat.setString(3, stu.getStuPhone());
            stat.setInt(4, stu.getStuId());
            int rtn = stat.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stat);
        }
    }

}
 

QueryAllServlet:

package com.hbc.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hbc.dao.StuDAO;


/**
 * Servlet implementation class QueryAllServlet
 */
@WebServlet("/QueryAllServlet")
public class QueryAllServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QueryAllServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //doGet(request, response);
        StuDAO dao = new StuDAO();
        List list = dao.queryAll();    
        request.setAttribute("stuList", list);
        request.getRequestDispatcher("show_jstl.jsp").forward(request, response);
//        request.getRequestDispatcher("show.jsp").forward(request, response);
    }

}
 

dbutil:

package com.hbc.bean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {

    static {
        //MySQL 5.7及以下使用的代码
        String driverClass="com.mysql.jdbc.Driver";
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }     // 加载数据库驱动
    }
    
    public DBUtil() {
        // TODO Auto-generated constructor stub
    }
    
    
    //获取数据库连接
    public static Connection getConnection() {
        String url="jdbc:mysql://localhost:3306/db_student";
        String username = "root";
        String password = "";
        Connection conn = null;
        try {
             conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    
    
    //获取静态语句操作对象
    public static Statement getStatement(Connection conn) {
        Statement stat = null;
        try {
            stat = conn.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stat;
    }
    
    //释放资源
    public static void closeAll(Connection connection, Statement statement,ResultSet resultSet){
        try {
            if (resultSet!=null){
                resultSet.close();
            }
            if (connection!=null){
                connection.close();
 
            }
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    //释放资源  (方法重载)
    public static void close(Connection connection, Statement statement){
        try {
            if (connection!=null){
                connection.close();
            }
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

 
}
 

index:

<%@ page language="java" import="javax.naming.*" pageEncoding="GB2312"%>
<%@ page import="javax.sql.*" %>
<%@ page import="java.sql.*" %>
<html>
<body>
<%
try {
      Context ctx = new InitialContext();
      ctx = (Context) ctx.lookup("java:comp/env");
      DataSource ds = (DataSource) ctx.lookup("TestJNDI");    //获取连接池对象
      Connection conn=ds.getConnection();
      Statement stmt=conn.createStatement();
      String sql="SELECT * FROM tb_user";
      ResultSet rs=stmt.executeQuery(sql);
    while(rs.next()){
        out.println("<br>用户名:"+rs.getString(2)+"    密码:"+rs.getString(3));
    }
      rs.close();
      stmt.close();
      conn.close();
} catch (NamingException e) {
      e.printStackTrace();
}
%>
</body>
</html>

show:

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.hbc.bean.StuBean" %>

<%    ArrayList stuList=(ArrayList)request.getAttribute("stuList");    %>

<table border="1" width="450" rules="none" cellspacing="0" cellpadding="0">
    <tr height="50"><td colspan="6" align="center">学生信息如下</td></tr>
    <tr align="center" height="30" bgcolor="lightgrey">
        <td>编号</td>
        <td>姓名</td>
        <td>性别</td>
        <td>电话</td>
        <td>操作1</td>
        <td>操作2</td>
    </tr>
    <%  if(stuList==null||stuList.size()==0){ %>
    <tr height="100"><td colspan="6" align="center">没有信息可显示!</td></tr>
    <% 
        } 
        else{
            for(int i=0;i<stuList.size();i++){
                StuBean stu = (StuBean)stuList.get(i);
    %>
    <tr height="50" align="center">
        <td><%=stu.getStuId()%></td>
        <td><%=stu.getStuName()%></td>
        <td><%=stu.getStuSex()%></td>
        <td><%=stu.getStuPhone()%></td>
        <td><a href="DeleteServlet?stuId=<%=stu.getStuId()%>">删除</a></td>
        <td><a href="ToUpdateServlet?stuId=<%=stu.getStuId()%>">修改</a></td>
    </tr>
    <%
            }
        }
    %>
</table>
 

show_jstl:

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.ArrayList" %>
<%@ page import="com.hbc.bean.StuBean" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%    ArrayList stuList=(ArrayList)request.getAttribute("stuList");    %>

<table border="1" width="450" rules="none" cellspacing="0" cellpadding="0">
    <tr height="50"><td colspan="6" align="center">学生信息如下</td></tr>
    <tr align="center" height="30" bgcolor="lightgrey">
        <td>编号</td>
        <td>姓名</td>
        <td>性别</td>
        <td>电话</td>
        <td>操作1</td>
        <td>操作2</td>
    </tr>
    
    <c:forEach items="${stuList}"  var="stu">
        <tr height="50" align="center">
            <td>${stu.stuId}</td>
            <td>${stu.stuName}</td>
            <td>${stu.stuSex}</td>
            <td>${stu.stuPhone}</td>
            <td><a href="DeleteServlet?stuId=${stu.stuId}">删除</a></td>
            <td><a href="ToUpdateServlet?stuId=${stu.stuId}">修改</a></td>
        </tr>
    </c:forEach>
    

</table>
 

mysql:

C:\Program Files\MySQL\MySQL Server 5.5\bin

mysqld --skip-grant-tables

  • 16
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值