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

1、安装所需软件

①安装java和tomcat,建立JSP网页最基础的软件
②安装MySQL数据库(下载地址:https://www.mysql.com/)
③安装Navicat Premium来查看数据库中的表
④下载JDBC驱动:mysql-connector-java-5.1.44-bin.jar(下载地址:https://www.mysql.com/products/connector/)
下载后把 mysql-connector-java-5.1.44-bin.jar 拷贝到 tomcat 下 lib 目录,如下图所示。
通过JSP网页连接MySQL数据库,从MySQL数据库中读出一张表并显示在JSP网页中

2、用Navicat Premium连接数据库,创建数据库和数据表

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

3.从MySQL数据库中读出student这个表并显示在JSP网页中

(1)确保tomcat和mysql是启动状态

(2)用Editplus编辑代码,保存在E: omcatapache-tomcat-7.0.88webappsROOT该目录下,如下图所示。

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

代码如下:

<%@ page contentType="text/html"%>  
<%@page pageEncoding="GB2312"%>  
<%@page import="java.sql.*" %>  <%--导入java.sql包--%>
<html>
<head>
<title >从MySQL数据库中读出student表</title>
</head>
<body>
<%  
        try {  
            Class.forName("com.mysql.jdbc.Driver");  ////驱动程序名
            String url = "jdbc:mysql://localhost:3306/study"; //数据库名
            String username = "root";  //数据库用户名
            String password = "123456";  //数据库用户密码
            Connection conn = DriverManager.getConnection(url, username, password);  //连接状态

            if(conn != null){  
                out.print("数据库连接成功!");  
                out.print("<br />"); 
%>
<table border="2">
<tr>
<td width="100" number="title">学号</td>
<td width="100" name="title">姓名</td>
<td width="100" age="title">年龄</td>
</tr>
<%
                Statement stmt = null;  
                ResultSet rs = null;  
                String sql = "SELECT * FROM student;";  //查询语句
                stmt = conn.createStatement();  
                rs = stmt.executeQuery(sql);  
                out.print("查询结果:");  
                out.print("<br/>");
                while (rs.next()) {%>
  <tr>  
    <td width="100" ><%=rs.getString("number") %></td>  
    <td width="100" ><%=rs.getString("name") %></td>  
    <td width="100"><%=rs.getString("age") %></td>  
  </tr>
  <%
            }  
            }else{  
                out.print("连接失败!");  
            }  
        }catch (Exception e) {        
            //e.printStackTrace();  
            out.print("数据库连接异常!");  
        }  
%> 
</table>
</body>
</html>

(3)在任意一个网页中输入http://localhost:8080/zza.jsp ,即可看到该student表。

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

参考链接:

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

2、JSP连接mysql数据库的重点

3、通过JSP网页连接Mysql数据库

4、JSP 连接数据库

5、JSP中使用JDBC连接MySQL数据库的详细步骤