Important Notice: ElephantSQL is shutting down. Read all about it in our End of Life Announcement

The recommended way to connect to postgres is via the jdbc client. Remember that you need to put the jdbc jar into your CLASS_PATH.

Good information about the connection string (connection URL), and information about how to initializing the driver can be found here.

//paste this into a file called
import java.sql.*;

public class Postgres {

    public static void main(String[] args) {
        try {
        catch (java.lang.ClassNotFoundException e) {

        String url = "jdbc:postgresql://host:port/database";
        String username = "database";
        String password = "password";

        try {
            Connection db = DriverManager.getConnection(url, username, password);
            Statement st = db.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM people");
            while ( {
                System.out.print("Column 1 returned ");
                System.out.print("Column 2 returned ");
        catch (java.sql.SQLException e) {


Java Spring

If you are using Spring, add org.postgresql and org.springframework spring-jdbc as dependencies.


This example will use a context.txt file including connection information. Add this bean to beans in your created context.txt.

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.postgresql.Driver"/>
  <property name="url" value="jdbc:postgresql://hostname:5432/username"/>
  <property name="username" value="username"/>
  <property name="password" value="password"/>

The DataSource uses the information from the context file to connect to ElephantSQL. The code in this example will create a table called elephant and insert some example data. It will then ask for the data with id = 2 and print it to the console.

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class SimpleElephantSQLExample
  public static void main(String []args)
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("context.xml");
    DataSource ds = (DataSource)applicationContext.getBean("dataSource");
    JdbcTemplate jt = new JdbcTemplate(ds);

    jt.execute("create table elephant (id int, name varchar)");
    jt.execute("insert into elephant (id, name) values (1, 'elephant_1')");
    jt.execute("insert into elephant (id, name) values (2, 'elephant_2')");

    Object[] parameters = new Object[] {new Integer(2)};
    Object o = jt.queryForObject("select name from elephant where id = ?",
      parameters, String.class);