AJP Lab Exercise-15


 15.Write down a program which demonstrates the SQL tag of JSTL.


----------------------------------



<%@ 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" %>
<html>
<head>
    <title>JSTL SQL Tag Example</title>
</head>
<body>
    <h2>JSTL SQL Tag Demonstration</h2>

    <!-- Step 1: Set Database Connection -->
    <sql:setDataSource var="db" 
        driver="com.mysql.cj.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC"
        user="root"
        password="root"/>

    <!-- Step 2: Create a Table (if not exists) -->
    <sql:update dataSource="${db}">
        CREATE TABLE IF NOT EXISTS students (
            id INT PRIMARY KEY AUTO_INCREMENT,
            name VARCHAR(50),
            course VARCHAR(50)
        )
    </sql:update>

    <!-- Step 3: Insert Data (only if the table is empty) -->
    <sql:update dataSource="${db}">
        INSERT INTO students (name, course) VALUES ('Nagaraju', 'Java')
    </sql:update>
    <sql:update dataSource="${db}">
        INSERT INTO students (name, course) VALUES ('Veera', 'NLP')
    </sql:update>

    <!-- Step 4: Retrieve Data -->
    <sql:query dataSource="${db}" var="result">
        SELECT * FROM students
    </sql:query>

    <!-- Step 5: Display Data -->
    <h3>Student Records</h3>
    <table border="1" cellpadding="5">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Course</th>
        </tr>
        <c:forEach var="row" items="${result.rows}">
            <tr>
                <td>${row.id}</td>
                <td>${row.name}</td>
                <td>${row.course}</td>
            </tr>
        </c:forEach>
    </table>

</body>
</html>