Java - PostgreSQL connection

Sample code for connecting to a PostgreSQL database using Java and simple queries.

The USERNAME, PASSWORD and DATABASE_NAME variables must be substituted with those supplied for your web hosting account.


  • <%@page import="java.sql.*"%>
    <html>
    <head>
            <title>Example page</title>
    </head>
    <body>
    <%
    
    out.println("Testing PostgreSQL jdbc<br />");
    
    try {
            Connection Conn = DriverManager.getConnection(
                    "jdbc:postgresql://localhost/DATABASE_NAME?user=USERNAME&password=PASSWORD");
    
            Statement Stmt = Conn.createStatement();
            ResultSet RS = Stmt.executeQuery("SELECT * FROM test");
    
            while (RS.next()) {
                    out.println(RS.getString(1));
            }
    
            // Clean up after ourselves
            RS.close();
            Stmt.close();
            Conn.close();
    }
    catch (SQLException E) {
          out.println("SQLException: " + E.getMessage());
          out.println("SQLState:     " + E.getSQLState());
          out.println("VendorError:  " + E.getErrorCode());
    }
    %>
    </body>
    </html>