JDBC connection using different files

First of all, sorry for the name of the name, but I do not know how to put another one, since English is not my native language.

I have the following way to connect to the database:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class PgConnect {
    public  void connect() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }
        if (connection != null) {
            System.out.println("Connection working");
        } else {
            System.out.println("Failed to make connection!");
        }
    }
}

And what I need to do is to include the method from PgConnectin the code below. Basically, I need this because I have many types of SQL database queries, and changing them this way would be easy to maintain, since the credentials / host would be in only one file.

I believe that the change should be where I have a comment

// i want to change this, for using the method on the first file. 

Please correct me if I am wrong.

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

public class ReturnResults {

    public static void main(String[] args) {
        Connection connection = null;
        try {
                // i want to change this, for using the method on the first file.
            connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }
        if (connection != null) {

            String result = null;
            String selectString = "select * from mwp.servers where env='TEST' order by server";
            //result ="iServer\tLabel\n";

            try {

                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(selectString);

                while (rs.next()) {

                    String iEnv     = rs.getString("env");
                    String iServer  = rs.getString("iserver");
                    String iLabel   = rs.getString("label");
                    String iTitle   = rs.getString("title");
                    String iLogin   = rs.getString("login");

                    result=iEnv+"\t"+ iServer+"\t"+iLabel+"\t"+iTitle+"\t"+iLogin;

                    System.out.println(result);
                }
                stmt.close();
                connection.close();

            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
            }

        } else {
            System.out.println("Failed to make connection!");
        }
    }
}

I know how to do this in Perl, but I have no practice in Java.

+5
source share
5 answers

connect , Connection, :

public class PgConnect {
    public static Connection connect() throws SQLException {
    try {
        Connection res = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        if (res != null) {
            System.out.println("Connection working");
        } else {
            System.out.println("Failed to make connection!");
        }
        return res;
    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        throw e;
    }
}

}

:

try {
    connection = PgConnect.connect();
} catch (SQLException e) {
    System.out.println("Connection Failed! Check output console");
    e.printStackTrace();
    return;
}
+3

connect() static, :

Connection con = PgConnect.connect();

Connection, Connection not void.

public static Connection connect() throws SQLException {
    try {
        Connection con = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        // ...
        return con;
    } 
    catch (SQLException e) {
        e.printStackTrace();
        return null;
    }

, . .

private static DataSource getOracleDBConnection() throws NamingException {
        Context c = new InitialContext();
        return (DataSource) c.lookup("java:comp/env/OracleDBConnection");
    }

    public static Connection getOracleDatabaseConnection() {

        Connection conn = null;
        try {
            conn = OracleDAOFactory.getOracleDBConnection().getConnection();
        } 
        catch (NamingException ex) {
            Logger.getLogger(OracleDAOFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
         catch (SQLException ex) {
            Logger.getLogger(OracleDAOFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }

NetBeans, , IDE, ALT+Insert, , " ..." Connection .

+3

, , return void :

public class PgConnect {
    //changing the method declaration to return a Connection
    public Connection connect() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return null;
        }
        if (connection != null) {
            System.out.println("Connection working");
        } else {
            System.out.println("Failed to make connection!");
        }
        return connection;
    }
}



public class ReturnResults {

    public static void main(String[] args) {
        Connection connection = null;
        PgConnect oPgConnect;
        try {
        //this is where you call your method object...
        oPgConnect = new PgConnect();
        //once created, you call the method to get the connection...
        connection = oPgConnect.connect();
        //after get the connection, keep with the method logic...
        if (connection != null) {
            //your logic code...
        }
    }
}
+1

, connect() PgConnect.java ReturnResults.java, Connection.

2 -

  • PgConnect.java ReturnResults.java public class ReturnResults extends PgConnect, connect.
  • PgConnect PgConnect.connect() ReturnResults.
+1

, , , sql? , , , .

, , , , ...

, Ive , , ..... ( , PGConnect.java , . SO . java/ .) , , , , Connection static, , . , , , .

package DatabaseCodePackage; //name you package something descriptive, its your call place both files into this package.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class PgConnect {

    public static Connection getConnection(String username, String password) throws SQLException
    {
        return DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", username, password);
    }

- .... SQL JDBC , , , , , -. . http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html . Ive SQL, .

package DatabaseCodePackage; //name you package something descriptive, its your call place both files into this package. 

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


public class ReturnResults {

public static void main(String[] args) {

     Stirng result = null; 
     try{
         result = selectAllWithEnv("TEST");

      // I catch exceptions here because i like to let exception pass entirely out of the
      // data layer, this way the control logic calling for the database information can decide what to do when it 
      // cant get the information it wants. This is especailly good in a MVC type project. 
    } catch (NullPointerException npe){
        result = "Connection Failed! Check output console : " + e.getMessage();
        e.printStackTrace();
        return;
    } catch (SQLException e) {
        result = "SQL failure! Check output console : " + e.getMessage();
        e.printStackTrace();
        return;
    } finally { 
        System.out.println(result); 
    }
}

public static String selectAllWithEnv(String var) throws SQLException, NullPointerException {
    String SQL = "select * from mwp.servers where env=? order by server";
    Connection connection = null;
    StringBuilder sb = new StringBuiler();
    try {
        connection = PgConnect.getConnection();
        PreparedStatement ps = connection.prepareStatement(SQL);
        ps.setObject(1, var);
        ResuletSet rs = ps.executeQuery();

        while (rs.next()) {

            String iEnv     = rs.getString("env");
            String iServer  = rs.getString("iserver");
            String iLabel   = rs.getString("label");
            String iTitle   = rs.getString("title");
            String iLogin   = rs.getString("login");

            sb.append(iEnv + "\t" + iServer + "\t" + iLabel + "\t" + iTitle + "\t" + iLogin + "\n");
         }
    } finally {
        connection.close();
    }
    return sb.toString();
}

, con.close() finally. . excetch try, . , , , . , , DBA - , . stmt.close() con.close(), , con.close()

0

All Articles