Corbin Hoenes writes:
> I am wondering which is the most effective way to display database
> information (i.e. say a table) w/JSP.
>
> I can't really find any examples on or anything so here is what I have
> come up with:
>
> create a bean that has 3 methods
>
> openDB()
> returnRow()
> closeDB()
>
> call the openDB() method open JDBC connection
> use a loop in the jsp file and call the returnRow() method to return one
> row
> closeDB() method to close resources.
>
> OR
>
> create a bean that opens,returns all the SQL query rows into a vector
> and then use another method that you call through the jsp file to
> iterate through the vector. The close the DB connection.
>
> ? Now am I way off here? Can I open a db connection inside a jsp
> scriptlet?
I did it this way. In the .jsp, I have something like
<%= bean.displayTableString() %>
It returns the string to draw the table in HTML. The variables 'conn'
and 'query' are instance variables of the class, initialized to an open
connection to the database and the SQL query to ask.
public String displayTableString()
throws java.sql.SQLException
{
String result;
Statement s;
ResultSet rs;
ResultSetMetaData meta;
int columns;
s = conn.createStatement();
rs = s.executeQuery(query);
meta = rs.getMetaData();
columns = meta.getColumnCount();
result = "<table border>";
// Column headers
result += "<tr>";
for (int i=0; i<columns; i++) {
result += "<th>" + meta.getColumnName(i+1) + "</th>";
}
result += "</tr>";
while (rs.next()) {
result += "<tr>";
for (int i=0; i<columns; i++) {
result += "<td>";
result += CGI.brIfNull(rs.getString(i+1));
result += "</td>";
}
result += "</tr>";
}
result += "</table>";
// Done with this statement
s.close();
return(result);
}
CGI.brIfNull is just:
static public String brIfNull(String s)
{
String result;
if ( s == null ) {
result = "<br>";
} else {
result = s;
}
return (result);
}
You did say you just wanted to DISPLAY the table. If you are returning
table rows for further processing in the body of the .JSP file, you will
have to return some data structure likea Vector or an Enumeration. Or
iterate through the rows in the .JSP if the size of the table might be
excessive to perhaps unnecessarily process every row.
--
Larry Mulcahy [EMAIL PROTECTED]
PGP Public key for [EMAIL PROTECTED] available at
http://wwwkeys.pgp.net:11371/pks/lookup?op=get&search=0xA339D6FD
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
FAQs on JSP can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html