JSTL <sql:query> 标签用来执行 SQL SELECT 语句,查询数据库中的数据。
JSP <sql:query> 标签的语法如下:
- <sql:query var="varname" [dataSource="dataSource"] [maxRows="maxRows"] [scope="page|session|request|application"] sql="sqlQuery" [startRow="startRow"]</sql:query>
其中:
下面为 <sql:query> 标签的简单示例。
创建 website 数据表,并插入数据。点击下载 SQL 文件(下载后需要解压)。
index.jsp 代码如下:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
- <!DOCTYPE html>
- <html>
- <head>
- <title>城东书院(www.cdsy.xyz)</title>
- </head>
- <body>
- <body>
- <sql:setDataSource var="test" driver="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost:3306/test" user="root" password="root" />
- <sql:query dataSource="${test}" var="result">
- SELECT * FROM website;
- </sql:query>
- <table border="1" width="100%">
- <tr>
- <th>id</th>
- <th>name</th>
- <th>url</th>
- <th>age</th>
- <th>country</th>
- </tr>
- <c:forEach var="row" items="${result.rows}">
- <tr>
- <td><c:out value="${row.id}" /></td>
- <td><c:out value="${row.name}" /></td>
- <td><c:out value="${row.url}" /></td>
- <td><c:out value="${row.age}" /></td>
- <td><c:out value="${row.country}" /></td>
- </tr>
- </c:forEach>
- </table>
- </body>
- </html>
运行结果如下: