通过JSP连接MySQL,从MySQL中读出一张表并显示在JSP网页中

一、工具

  1. MySQL数据库
  2. Navicat Premium
  3. Java Platform (JDK) 10
  4. Tomcat 9.0.10
  5. Notepad ++
  6. mysql-connector-java-5.1.7-bin.jar (java连接MySQL工具包)
    以上是用到的全部工具,需要安装及配置,详见我前面的文章。

二、用 Navicat Premium 创建数据表

方法不赘述,详见:https://blog.csdn.net/yangchenju/article/details/80633055
新建连接;
这里写图片描述
我随机建的表如下:
这里写图片描述

三、其他准备工作

  1. 将“java连接MySQL工具包”文件拷贝到Tomcat安装目录下的lib文件中
    这里写图片描述
  2. 启动Tomcat服务器
    在安装文件夹下找到 bin 文件夹,然后找到 startup.bat —->打开
    这里写图片描述

  3. 启动mysql数据库
    这里写图片描述

四、代码

打开 Notepad ++ 编写jsp代码,并保存到Tomcat安装目录下的 webapps\ROOT 中,保存类型为.jsp文件。
我的代码如下:

<%@page contentType="text/html"%>  
<%@page pageEncoding="UTF-8"%>  //是能够显示中文
<%@page import="java.sql.*" %>//导入所有sql的包
<html>
<head><title>成绩表</title></head>  //网页标题
<body>
<%  //Java语句
        try {  
            Class.forName("com.mysql.jdbc.Driver");  // 加载驱动
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/learning",
                "root", "root");  ////获取Connection对象

            if(con != null){         
                Statement stmt = null;  
                ResultSet rs = null;  
                String sql = "SELECT *FROM scores;";  //查询语句
                stmt = con.createStatement();  
                rs = stmt.executeQuery(sql); 
%>
    <table border="1" cellspacing="0" cellpadding="0" align="center" width="50%">//这是css语句,建立表格,并对变革进行外观描述
<tr>//第一行,表头形式
<th><%out.print("id");%></th>
<th><%out.print("name");%></th>
<th><%out.print("chinese");%></th>
<th><%out.print("english");%></th>
<th><%out.print("math");%></th> 
</tr>
<% while (rs.next()) {%>  //这是一个循环,读取数据库中的数据
<tr align="center"> //从第二行起为都出来的数据,显示时居中
<td><%out.print(rs.getInt("id"));%></td>
<td><%out.print(rs.getString("NAME"));%></td>
<td><%out.print(rs.getInt("chinese"));%></td>
<td><%out.print(rs.getInt("english"));%></td>
<td><%out.print(rs.getInt("math"));%></td>
</tr>
<%}%>//循环结束
</table>
<%
            }else{  
                out.print(“Connection fail!");  
            }  
        }catch (Exception e) {        
            //e.printStackTrace();  
            out.print("Connection Exception!");  
        }  
%>
</body>
</html>

五、从MySQL中读出一张表并显示在JSP网页中

  1. 查询本机IP地址:
    这里写图片描述
    打开浏览器,输入:http://192.168.43.63:8080/2.jsp
IP地址 + :8080 + .jsp文件

回车后:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Yangchenju/article/details/80868795
今日推荐