/**
* JDBCServlet.java
* Example of JDBC usage in a servlet
* @author Nauman Chaudhry
* 02/11/08
*/
package classExamples;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Import JDBC API to be used in the example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
public class JDBCServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
writeHTMLHead(out);
Connection conn = null;
Statement stmt = null;
ResultSet rSet = null;
try{
out.println("Trying to load driver
");
Class.forName("oracle.jdbc.OracleDriver");
// Error checking should be done here!
String dbhost = getServletContext().getInitParameter("dbhost");
String dbport = getServletContext().getInitParameter("dbport");
String dbsid = getServletContext().getInitParameter("dbsid");
String dbuser = getServletContext().getInitParameter("dbuser");
String dbpwd = getServletContext().getInitParameter("dbpwd");
String dbURL = getDbURL(dbhost, dbport, dbsid);
out.println("
Trying to create connection with URL: " + dbURL);
getServletContext().log("dbURL: " + dbURL);
conn = DriverManager.getConnection(dbURL, dbuser, dbpwd);
// Create and execute a SQL statement
stmt = conn.createStatement();
rSet = stmt.executeQuery(
"SELECT TABLE_NAME FROM USER_TABLES");
out.println("
Executed SQL");
out.println("
Tables are:");
while(rSet.next()){
out.println("
" + rSet.getString("TABLE_NAME"));
}
}
catch(ClassNotFoundException e){
// In an actual application we will not send the error message
// to the user, but will simply log the error.
getServletContext().log("Unable to load Driver class", e);
out.println("
Unable to load Driver class");
}
catch(SQLException se){
getServletContext().log("SQL Exception", se);
out.println("SQL Exception: " + se.getMessage() + "
");
se.printStackTrace(out);
}
finally{
try{
if(rSet!=null){
rSet.close();
}
if(stmt !=null){
stmt.close();
}
if (conn != null){
conn.close();
}
}
catch(SQLException se){
getServletContext().log("SQL Exception", se);
}
writeHTMLTail(out);
}
}
private String getDbURL(String dbhost, String dbport, String dbsid){
return "jdbc:oracle:thin:@" + dbhost + ":" + dbport + ":" + dbsid;
}
private void writeHTMLHead(PrintWriter out){
out.println("");
out.println("