get Connection to postgresql - Java java.sql

Java examples for java.sql:PostgreSQL

Description

get Connection to postgresql

Demo Code


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.util.Properties;

public class Main{
    public static void main(String[] argv) throws Exception{
        System.out.println(getConnection());
    }/*from   ww  w  . j  a  v a 2 s  .  co m*/
    public static Connection getConnection()
            throws Ser422DbWrapperException {
        // read info from default properties if needed
        //   return getConnection(jdbcUser, jdbcPasswd, jdbcURL, jdbcDriver);
        String url = "jdbc:postgresql://localhost:5432/patient";
        Properties props = new Properties();
        props.setProperty("user", "ser422");
        props.setProperty("password", "database");
        //props.setProperty("compatible", "7.1");

        return getConnection(url, props, "org.postgresql.Driver");
    }
    public static Connection getConnection(String jdbcUser,
            String jdbcPasswd, String jdbcURL, String jdbcDriver)
            throws Ser422DbWrapperException {
        Properties props = new Properties();
        props.setProperty("user", jdbcUser);
        props.setProperty("password", jdbcPasswd);
        //props.setProperty("compatible", "7.1");

        return getConnection(jdbcURL, props, jdbcDriver);
    }
    public static Connection getConnection(String url, Properties props,
            String jdbcDriver) throws Ser422DbWrapperException {
        try {
            Class.forName(jdbcDriver);
            return DriverManager.getConnection(url, props);
        } catch (Throwable t) {
            t.printStackTrace();
            throw new Ser422DbWrapperException(
                    "Ser422DbUtils::getConnection", t);
        }
    }
}

Related Tutorials