Postgres Connections in JSP

From Lunarpages Web Hosting Wiki

How do I connect to my PostGRESQL database using JSP?

Please use the following code for connecting to your database, replacing the String url cpanelusername_dbname portion, the String username cpanelusername_dbusername portion, and the String password portion:

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.* " %>
<%@ page import="*" %>
try {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost:5432/cpanelusername_dbname";
String username = "cpanelusername_dbusername";
String password = "sqltest";
String myDataField = null;
String myQuery = "SELECT * FROM sample LIMIT 1";
Connection myConnection = null;
PreparedStatement myPreparedStatement = null;
ResultSet myResultSet = null;
myConnection = DriverManager.getConnection(url,username,password);
myPreparedStatement = myConnection.prepareStatement(myQuery);
myResultSet = myPreparedStatement.executeQuery();
myDataField = myResultSet.getString("dispname");
catch(ClassNotFoundException e){e.printStackTrace();}
catch (SQLException ex)
out.print("SQLException: "+ex.getMessage());
out.print("SQLState: " + ex.getSQLState());
out.print("VendorError: " + ex.getErrorCode());

Please note: The above will attempt to connect to a table called sample, so you would want to change or update this appropriately per your own table(s) and coding.