แท็ก <sql:query> ใช้สำหรับรันคำสั่ง SQL SELECT และเก็บผลลัพธ์ไว้ในตัวแปรที่มีขอบเขต (scoped variable)
แอตทริบิวต์ของ <sql:query>
| แอตทริบิวต์ | คำอธิบาย | จำเป็น | ค่าเริ่มต้น |
|---|---|---|---|
| sql | คำสั่ง SQL ที่ต้องการรัน (ต้องคืน ResultSet) | ไม่ | Body |
| dataSource | การเชื่อมต่อฐานข้อมูล (ทับค่าเริ่มต้นได้) | ไม่ | Default database |
| maxRows | จำนวนแถวสูงสุดที่จะเก็บในตัวแปร | ไม่ | Unlimited |
| startRow | ลำดับแถวเริ่มต้นในผลลัพธ์ (เริ่มจาก 0) | ไม่ | 0 |
| var | ชื่อตัวแปรสำหรับเก็บผลลัพธ์ | ไม่ | Set default |
| scope | ขอบเขตของตัวแปรผลลัพธ์ | ไม่ | Page |
ตัวอย่างสมบูรณ์: สร้างตาราง ข้อมูล และ Query
ขั้นตอนสร้างตาราง Employees ใน MySQL
mysql> use TEST;
mysql> create table Employees (
id int not null,
age int not null,
first varchar(255),
last varchar(255)
);
Query OK, 0 rows affected (0.08 sec)
เพิ่มข้อมูลตัวอย่าง
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
ไฟล์ JSP สำหรับ Query และแสดงผล
<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="https://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<html>
<head>
<title>JSTL sql:query Tag</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
<table border="1" width="100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
ผลลัพธ์ที่ได้
+-------------+----------------+-----------------+-----------------+ | Emp ID | First Name | Last Name | Age | +-------------+----------------+-----------------+-----------------+ | 100 | Zara | Ali | 18 | | 101 | Mahnaz | Fatma | 25 | | 102 | Zaid | Khan | 30 | | 103 | Sumit | Mittal | 28 | +-------------+----------------+-----------------+-----------------+
หมายเหตุ: ควรใช้ Connection Pool (DataSource) ในการใช้งานจริง แทนการสร้างการเชื่อมต่อใหม่ทุกครั้ง