[ Team LiB ] |
![]() ![]() |
Using JDBC from JavaServer Pages and ServletsJDBC can be used through any piece of Java code, including JavaServer Pages or servlets. The following JSP is an example of using JDBC to access the People table in the database, PeopleDB. Listing 18.1 shows a JSP that queries a Person table using JDBC. Listing 18.1 Source Code for ShowPeople.jsp<html> <head> <title>JDBC Example for People Table</title> </head> <body> <%@ page language="java" import="java.sql.*, java.io.*" %> <% Connection con = null; try Class.forName("com.ibm.db2j.jdbc.DB2jDriver");{ con = DriverManager.getConnection("jdbc:db2j:PeopleDB"); Statement statement = con.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM People"); %> <table border="1"><tr><th>Name</th><th>Age</th> <% while ( rs.next() ) { out.println("<tr>\n<td>" + rs.getString("name") + "</td>"); out.println("<td>" + rs.getByte("age") + "</td>"); + "</td>\n</tr>"); } rs.close(); } catch (IOException ioe) { out.println(ioe.getMessage()); } catch (SQLException sqle) { out.println(sqle.getMessage()); } catch (Exception e) { out.println(e.getMessage()); } finally { try { if ( con != null ) { con.close(); } } catch (SQLException sqle) { out.println(sqle.getMessage()); } } %> </tr> </table> </body> </html> This simple JSP uses straight JDBC calls to print all the rows in the People table. You will see later in this hour how this lengthy and complicated JDBC code is greatly simplified using the JSTL SQL tag libraries. Running the Example
![]() |
[ Team LiB ] |
![]() ![]() |