WHAT'S NEW?

Loading Data from Database in HTML Table using JDBC

JSP File below shows how to load data from a Database Table using JDBC and JSP.



dataload.jsp


<%@ page import="java.sql.* %>

<html>
 <head>
  <title> Data Load in JSP</title>

  <style>
  #customers
{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width:100%;
border-collapse:collapse;
}
#customers td, #customers th 
{
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#customers th 
{
font-size:1.1em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#ffffff;
}
#customers tr.alt td 
{
color:#000000;
background-color:#EAF2D3;
}

</style>

 </head>

 <body>
 <center>Data Loading</a>
 <table border=2 id="customers">

 <%

 ResultSet rs=null;
 ResultSetMetaData rsmd=null;
// int i=0;
 //int j=0;
 String data[][];
  try
{

Class.forName("com.mysql.jdbc.Driver");
Connection con=Drivermanager.getConnection("jdbc:mysql://localhost:3306/yourdb","youruser","yourpassword");
Statement stmt=con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,
                                      ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("select * from lkdata;");
rsmd = rs.getMetaData();
int col = rsmd.getColumnCount();

String[] ch = new String[col];

out.println("<tr>");
for(int co=0; co< col; co++) 
{
ch[co] = rsmd.getColumnName(co+1);

%>


<th> <%= ch[co].toUpperCase()%>

</th>


<%

}
out.println("</tr>");
int row = 0;
while(rs.next()) row++;   

data = new String[row][col];
rs.beforeFirst();


for(int i = 0;rs.next();i++)
{
if(i%2==0)
{
out.println("<tr>");

for(int j=0; j<col; j++)
{

String s = rs.getString(j+1);
%>
<td> <%=s%></td>


<%
}
out.println("</tr>");
}
else
{
%>
<tr class="alt">
<%

for(int j=0; j<col; j++)
{

String s = rs.getString(j+1);
%>
<td> <%=s%></td>


<%
}
out.println("</tr>");
}
}
%>
</table>
<%
}
catch(Exception e)
{
e.printStackTrace(new java.io.PrintWriter(out));
}
%>

 </body>
</html>

0 comments:

Post a comment