JSP查询操作

表格

<%--
  Created by IntelliJ IDEA.
  User: 和
  Date: 2020/10/7
  Time: 8:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form action="home.jsp " method=&
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSP 本身并不支持数据库查询,需要借助 Java 的 JDBC(Java Database Connectivity)技术来实现。下面是一个简单的 JSP 连接 MySQL 数据库进行连表查询的示例: 假设有两张表:`students`(学生表)和 `grades`(成绩表),它们之间的关系是一个学生可以对应多个成绩记录。 1. 在 JSP 页面中引入 JDBC 相关的类库: ```java <%@ page import="java.sql.*" %> ``` 2. 使用 JDBC 连接 MySQL 数据库: ```java <% // 定义数据库连接信息 String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; // 加载 MySQL 驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 Connection conn = DriverManager.getConnection(url, username, password); %> ``` 3. 编写 SQL 查询语句,并执行查询操作: ```java <% // 编写 SQL 查询语句 String sql = "SELECT * FROM students s JOIN grades g ON s.id = g.student_id"; // 创建 Statement 对象 Statement stmt = conn.createStatement(); // 执行查询操作 ResultSet rs = stmt.executeQuery(sql); %> ``` 4. 在 JSP 页面中输出查询结果: ```java <table> <thead> <tr> <th>学生姓名</th> <th>课程名称</th> <th>成绩</th> </tr> </thead> <tbody> <% while (rs.next()) { %> <tr> <td><%= rs.getString("name") %></td> <td><%= rs.getString("course") %></td> <td><%= rs.getInt("score") %></td> </tr> <% } %> </tbody> </table> ``` 完整的 JSP 代码如下: ```java <%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="java.sql.*" %> <html> <head> <title>学生成绩查询</title> </head> <body> <h1>学生成绩查询</h1> <% // 定义数据库连接信息 String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; // 加载 MySQL 驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 Connection conn = DriverManager.getConnection(url, username, password); // 编写 SQL 查询语句 String sql = "SELECT * FROM students s JOIN grades g ON s.id = g.student_id"; // 创建 Statement 对象 Statement stmt = conn.createStatement(); // 执行查询操作 ResultSet rs = stmt.executeQuery(sql); %> <table> <thead> <tr> <th>学生姓名</th> <th>课程名称</th> <th>成绩</th> </tr> </thead> <tbody> <% while (rs.next()) { %> <tr> <td><%= rs.getString("name") %></td> <td><%= rs.getString("course") %></td> <td><%= rs.getInt("score") %></td> </tr> <% } %> </tbody> </table> <% // 关闭数据库连接 rs.close(); stmt.close(); conn.close(); %> </body> </html> ``` 注意:上述示例代码仅供参考,实际使用时需要根据具体情况进行修改和优化。同时,为避免 SQL 注入等安全问题,应该对用户输入的参数进行校验和过滤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值