jsp数据库操作之查询

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/JY_WD/article/details/101125177

准备

通过Mysql建立数据库webstore,建立表格user_table。如下图
在这里插入图片描述

注意:上面的列名我用的汉字,可以转换为英文(推荐)后面的代码,要与这个列名一一对应,自己体会。

代码:

select.jsp

<%--
  Created by IntelliJ IDEA.
  User: 长风
  Date: 2019/9/21
  Time: 19:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.sql.*" %>
<html>
<head>
    <title>管理员页面</title>
</head>
<body>
<%!
    public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    //    驱动路径
    public static final String DBURL = "jdbc:mysql://localhost:3306/webstore?&useSSL=false&serverTimezone=UTC";
    //    webstore是我数据库的名字,?&useSSL=false&serverTimezone=UTC防止报错和乱码。
    public static final String DBUSER = "root";
    //    数据库用户名
    public static final String DBPASS = "123456";
    //    数据库密码
%>

<%
    /*这里的一下参数也可以去下面定义*/
    Connection conn = null;
    /*定义一个创建连接的变量,初始值设为空,当需要连接时,通过
    Connection conn=DriverManager.getConnection(URL,Username,Password);
    去创建连接, 方便后面关闭操作*/
    PreparedStatement pst = null;
    /*Statement和PreparedStatament的区别
    Statement执行查询调用方法executeQuery(sql)
    执行更删改调用方法executeUpdate(sql)
    PreparedStatement执行查询调用方法executeQuery()
    执行更删改调动方法executeUpdate()*/
    ResultSet rs = null;
%>
<%
    try {
        Class.forName(DBDRIVER);
        //注册驱动
        conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
        //获取链接
        request.setCharacterEncoding("utf-8");
        String sql_select = "select * from user_table";
        //获取操作数据库对象,注意这里的user_table是我数据库里面的一个表
        pst = conn.prepareStatement(sql_select);
        rs = pst.executeQuery();
        //执行sql_select,获取结果集
%>
<table border="1">
    <tr>
        <td>id</td>
        <td>用户名</td>
        <td>密码</td>
        <td>用户类型</td>
        <td colspan="2" align="center">数据操作</td>
    </tr>
    <%
        while (rs.next()) {
            //处理结果
    %>
    <tr>
        <td><%= rs.getString(1) %>
        </td>
        <td><%= rs.getString("用户名")%>
        </td>
        <td><%= rs.getString("密码")%>
        </td>
        <td><%= rs.getString("用户类型")%>
        </td>
        <td>
            <button><a href="delete.jsp?id=<%=rs.getString("id")%>">删除该记录</a></button>
        </td>
        <td>
            <button><a href="update.jsp?id=<%=rs.getString("id")%>">更新该记录</a></button>
        </td>
    </tr>
    <%
            }
        } catch (Exception e) {
            out.println(e);
        }
    %>
    <tr>
        <td>
            <button><a href="insert.jsp">插入</a></button>
        </td>
    </tr>
</table>

</body>
</html>


运行结果

在这里插入图片描述

关于数据库插入,更新,删除。见博客其他文章。嘿嘿。

猜你喜欢

转载自blog.csdn.net/JY_WD/article/details/101125177