Postgres Connections in JSP

From Lunarpages Web Hosting Wiki
Jump to: navigation, search

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="java.io.*" %>
<%
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;
Class.forName(driver).newInstance();
myConnection = DriverManager.getConnection(url,username,password);
myPreparedStatement = myConnection.prepareStatement(myQuery);
myResultSet = myPreparedStatement.executeQuery();
if(myResultSet.next())
myDataField = myResultSet.getString("dispname");
out.print(myDataField);
}
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.

Share |
Want to read this in another language?