Retrieve data from database by using sql tag of JSTL SQL library
Here in this section we will see how retrieve data from database using sql query given by user. To execute query first create a data source and then execute sql query for that data source.
<sql:setDataSource> : This tag is used to create data source for specified driver, user name and password of database, url etc. | ||||||||||||||
Attributes of
the tag <sql:setDataSource>
|
After creating connection to database, now we are explaining how to execute sql query. To execute sql query we have used a sql tag <sql:query>, it executes sql and stores result in specified variable.
<sql:query> : This tag is used to create data source for specified driver, user name and password of database, url etc. | ||||||||||||
Attributes of
the tag <sql:setDataSource>
|
Before run this code first create a database named 'mahendra'
and table named 'employee_master' in same database by the sql query given below:
Query to create table:
CREATE TABLE `employee_master` ( `emp_id` int(10) NOT NULL auto_increment, `firstName` varchar(20) default NULL, `lastname` varchar(20) default NULL, `salary` double default NULL, `tonus` double default NULL, PRIMARY KEY (`emp_id`) )
|
Structure of the table: |
retrieve_database_SqlJstlTag.jsp
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%> <sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mahendra" user="root" password="root" /> <html> <head> <title>Query Example</title> </head> <body> <sql:query var="users" dataSource="${dataSource}"> select* from employee_master; </sql:query> <table border=1> <c:forEach var="row" items="${users.rows}"> <tr> <td><c:out value="${row.emp_id}" /></td> <td><c:out value="${row.firstName}" /></td> <td><c:out value="${row.lastname}" /></td> <td><c:out value="${row.salary}" /></td> <td><c:out value="${row.bonus}" /></td> </tr> </c:forEach> </table> </body> </html>
Steps to run this example :
1: Download the zip file of code and unzip this
file, you will get a folder named 'retrieve_database_SqlJstlTag'.
2: Paste this folder in 'Apache Tomcat 6.0.16-->webapps' or generally
in directory 'C:\apache-tomcat-6.0.16\webapps'.
3: Start tomcat server by click on startup.bat file in
'C:\apache-tomcat-6.0.16\bin'.
4: Open browser and type url 'http://localhost:8080/retrieve_database_SqlJstlTag/retrieve_database_SqlJstlTag.jsp'
or click on this link.
Output of the program