get postgresql Connection - Java java.sql

Java examples for java.sql:PostgreSQL

Description

get postgresql Connection

Demo Code


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main{
    private static Connection conn = null;
    private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
    private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/postgres";
    private static final String DEFAULT_USERNAME = "traw";
    private static final String DEFAULT_PASSWORD = "root";
    public static Connection getConnection() {

        if (conn != null) {
            return conn;
        }//ww w  . ja v a  2s. co  m

        try {

            Class.forName(DEFAULT_DRIVER).newInstance();

        } catch (ClassNotFoundException | InstantiationException
                | IllegalAccessException ex) {
            System.err.println("ClassNotFoundException Occured: "
                    + ex.getMessage());
        }

        try {
            conn = DriverManager.getConnection(DEFAULT_URL,
                    DEFAULT_USERNAME, DEFAULT_PASSWORD);
        } catch (SQLException sqlEx) {
            System.err.println("SQLException Occured: "
                    + sqlEx.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return conn;
    }
    @Override
    public void close() throws Exception {
        closeConnection();
    }
    public static void closeConnection() {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            System.err.println("SQLException Occured: " + ex.getMessage());
        }
    }
}

Related Tutorials