<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*,javax.naming.*,javax.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Data Source</title>
</head>
<body>
<h1>Test Data Source</h1>
<p>Hello</p>
<%
DataSource ds = null;
Connection con = null;
Statement stmnt = null;
ResultSet resultSet = null;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DataSource");
con = ds.getConnection();
stmnt = con.createStatement();
resultSet = stmnt.executeQuery("select * from PERSON");
if (resultSet != null) {
%><table><tr><%
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int nOfColumns = resultSetMetaData.getColumnCount();
for(int j = 0; j<nOfColumns; j++) {
String columnLabel = resultSetMetaData.getColumnLabel(j+1);
%><th><%=columnLabel %></th><%
}
%></tr><%
if (resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY) {
resultSet.beforeFirst();
}
while (resultSet.next()) {
%><tr><%
for (int i = 1; i <= nOfColumns; ++i) {
%><td><%
Object value = resultSet.getObject(i);
if (resultSet.wasNull()) {
%><b>null</b><%
} else {
%><%=value.toString() %><%
}
%></td><%
}
%></tr><%
}
%></table><%
}
} catch(NamingException e) {
throw e;
} catch(SQLException e) {
throw e;
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
}
resultSet = null;
try {
if (stmnt != null) {
stmnt.close();
}
} catch (SQLException e) {
}
stmnt = null;
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
}
con = null;
ds = null;
}
%>
</body>
</html>
Just change
java:comp/env/jdbc/DataSource
To what the name of your DataSource connection pool is.
Then change
select * from PERSON
To a test query from this table:
Cloudscape | #SQL SELECT 1 |
#DB2 | #SQL SELECT COUNT(*) FROM SYSIBM.SYSTABLES |
#Informix | #SQL SELECT COUNT(*) FROM SYSTABLES |
#Microsoft SQL Server | #SQL SELECT COUNT(*) FROM SYSOBJECTS |
#MySQL | #SQL SELECT 1 |
#Oracle | #SQL SELECT 1 FROM DUAL |
#PointBase | #SQL SELECT COUNT(*) FROM SYSTABLES |
#PostgreSQL | #SQL SELECT 1 |
#Progress | #SQL SELECT COUNT(*) FROM SYSTABLES |
#Sybase | #SQL SELECT COUNT(*) FROM SYSOBJECTS |
Do not use this code to interact with a datasource, this should only be used for figuring out what the name of a datasource you created in the J2ee container is and that it is working.
No comments:
Post a Comment