Database Tag Library in JSP
What is Database Tag Library in JSP?
Explanation
Database Tag Library lists the tags that are used for database connectivity in JSP pages. All these tags are used for quick design of database connectivity in simple applications, but in large application database connectivity is embedded using Java beans. The database tags have the prefix "sql".
Syntax:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
Function | Tags |
Setting the data source | setDataSource |
SQL | query,transaction,update |
Example for INSERT Query:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql"
prefix="sql"%>
<html>
<head>
<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test" user="root" password=""
scope="session" />
<sql:update dataSource="${dataSource}" var="updttble">
INSERT INTO emp(id,name,salary) VALUES(2,"alex","3000")
</sql:update>
In the above example we have used the "<sql:setDataSource/>" tag to define the driver location. Here the "driver" attribute specifies the JDBC driver, the "url" attribute specifies the JDBC url for the database connection with the database name, the attribute "user", "password" specifies the username, password for the database, "scope" of connection. We have used the "INSERT" query to update the table with the "id=2", "name=alex", "salary=3000". Example for SELECT query:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/test" user="root" password="" scope="session"/>
<sql:query var = "qry" dataSource="${dataSource}">
SELECT id,name FROM emp
</sql:query>
<table>
<c:forEach var="row" items="${qry.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.name}"/></td>
</tr>
</c:forEach>
</table>
</html>
Result :
In the above example we have used the tag "<sql:query" and the "SELECT" query to get the records with only the "id" and "name" alone form the table "emp".