JSTL SQL Tags

In JSTL, SQL tags are used to access and manipulate various operations of database. It is responsible to interact the JSP page with any type of Database such as MySQL, Oracle, SQLite, etc. The below syntax is used to include SQL library within JSP: -

<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>

SQL Tags

These are some important JSTL SQL tags: -

  • <sql:setDataSource>: - This tag creates a DataSource to  communicate JSP with database server.
  • <sql:query>: - This tag executes the SQL query that is specified with it.
  • <sql:transaction>: - This tag performs various database action with single connection.
  • <sql:param>: - This tag provides parameter to SQL statement.
  • <sql:dateParam>:  - This tag provides date in the form of parameter to SQL statement.
  • <sql:update>: - This tag is used to update the value in database.

Example of JSTL SQL Tag

This is a simple example of JSTL SQL Tag that fetches data from MYSQL.

index.jsp

<%@ page import="java.io.*,java.util.*,java.sql.*"%> 
<%@ page import="javax.servlet.http.*,javax.servlet.*" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> 
<html> 
<head> 
<title>sql:query Tag</title> 
</head> 
<body> 
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver" 
     url="jdbc:mysql://localhost/jtp_gym" 
     user="root"  password=""/> 
<sql:query dataSource="${db}" var="rs"> 
SELECT * from admin; 
</sql:query>   
<table border="2" width="100%"> 
<tr> 
<th>Student ID</th> 
<th>Password</th> 
<th>U Id</th>   
</tr> 
<c:forEach var="table" items="${rs.rows}"> 
<tr> 
<td><c:out value="${table.id}"/></td> 
<td><c:out value="${table.password}"/></td> 
<td><c:out value="${table.user_id}"/></td> 
</tr> 
</c:forEach> 
</table> 
</body> 
</html>
Output: