Development Island

Using JDBC with servlets

This page gives brief details how to access your database via a servlet using JDBC.
Note that connection details do not need to be supplied as your datasource as been preconfigured. Datasources are available by using the JNDI name of "java:comp/env/jdbc/db_username" where username should be replaced with your account name. Please note that Postgres users should use the JNDI name of "java:comp/env/jdbc/pgdb_username" instead.

Next is example servlet code showing the connecting to a database and submition of a simple query.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

public class ExampleServlet extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
   	throws ServletException, IOException{

		//Get the client's output stream
		PrintWriter out;
		response.setContentType("text/html");
		out = response.getWriter();
		DataSource ds = null;
		Connection c = null;
		Statement Stmt = null;
		ResultSet RS = null;
		try{
			Context initCtx = new InitialContext();
			ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/db_user");
			c = ds.getConnection();
			//Create a new session with the database
			Stmt = c.createStatement();
			//Query the database
			RS = Stmt.executeQuery("SELECT field1 FROM atable WHERE (field2 ='foo')");
			while (RS.next()) {
				//Print out results
				out.println(RS.getString("field1"));
			}
		}
		//Catch Errors
		catch(Exception e){
			out.println("ERROR:"+e.getMessage());
		}
		finally{
			try{
				if(RS != null){
					RS.close();
				}
				if(Stmt != null){
					Stmt.close();
				}
				if(c != null){
					c.close();
				}
			}
			catch(Exception e2){
				out.println("Unable to close connection: "+e2.getMessage());		
			}
		}
		//Close output stream to client
		out.close();
	}
}