JDBC select
This will get records from database and print and view on JSP page. The SQL query is used as select command statement, and with while loop we can view all records in table.
Example of select record in database through JSP
selectRecords.jsp
HTML Code Example
<%@ page language="java" import="java.sql.*" errorPage="" %>
<%
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcURL="jdbc:mysql://localhost:3306/jsp";
conn = DriverManager.getConnection(jdbcURL,"root", "");
PreparedStatement psSelectRecord=null;
ResultSet rsSelectRecord=null;
String sqlSelectRecord=null;
sqlSelectRecord ="SELECT * FROM staff_register";
psSelectRecord=conn.prepareStatement(sqlSelectRecord);
rsSelectRecord=psSelectRecord.executeQuery();
%>
<html>
<head>
<title>View records in JSP through database</title>
<style>
td
{
text-align:center
}
</style>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="12%"> </td>
<td width="16%"> </td>
<td width="24%"> </td>
<td width="22%"> </td>
<td width="26%"> </td>
</tr>
<tr>
<td colspan="5" align="center">View Record from Database through JSP </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<th>S. No </th>
<th>EmpID</th>
<th>Staff Name </th>
<th>Staff Department </th>
<th>Staff Phone </th>
</tr>
<%
int cnt=1;
while(rsSelectRecord.next())
{
%>
<tr>
<td><%=cnt%></td>
<td><%=rsSelectRecord.getString("iEmpID")%> </td>
<td><%=rsSelectRecord.getString("sStaffName")%> </td>
<td><%=rsSelectRecord.getString("sStaffDept")%> </td>
<td><%=rsSelectRecord.getString("iStaffPhone")%> </td>
</tr>
<%
cnt++; /// increment of counter
} /// End of while loop
%>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
<%
try{
if(psSelectRecord!=null)
{
psSelectRecord.close();
}
if(rsSelectRecord!=null)
{
rsSelectRecord.close();
}
if(conn!=null)
{
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
|