|
1 | | -package merhoo.backend; |
| 1 | +package edu.lehigh.cse216.mfs409.admin; |
| 2 | + |
| 3 | +import java.sql.Connection; |
| 4 | +import java.sql.DriverManager; |
| 5 | +import java.sql.SQLException; |
| 6 | +import java.util.Map; |
2 | 7 |
|
3 | 8 | /** |
4 | | - * Hello world! |
5 | | - * |
| 9 | + * App is our basic admin app. For now, all it does is connect to the database |
| 10 | + * and then disconnect |
6 | 11 | */ |
7 | | -public class App |
8 | | -{ |
9 | | - public static void main( String[] args ) |
10 | | - { |
11 | | - System.out.println( "Hello World!" ); |
| 12 | +public class App { |
| 13 | + /** |
| 14 | + * The main routine reads arguments from the environment and then uses those |
| 15 | + * arguments to connect to the database. |
| 16 | + */ |
| 17 | + public static void main(String[] argv) { |
| 18 | + // get the Postgres configuration from the environment |
| 19 | + Map<String, String> env = System.getenv(); |
| 20 | + String ip = env.get("POSTGRES_IP"); |
| 21 | + String port = env.get("POSTGRES_PORT"); |
| 22 | + String user = env.get("POSTGRES_USER"); |
| 23 | + String pass = env.get("POSTGRES_PASS"); |
| 24 | + |
| 25 | + // Some students find that they need the following lines |
| 26 | + // *before DriverManager.getConnection* in order to get the postgres |
| 27 | + // driver to load |
| 28 | + |
| 29 | + // try { |
| 30 | + // Class.forName("org.postgresql.Driver"); |
| 31 | + // } catch (ClassNotFoundException cnfe) { |
| 32 | + // System.out.println("Unable to find postgresql driver"); |
| 33 | + // return; |
| 34 | + // } |
| 35 | + |
| 36 | + // conn is a connection to the database. In this simple example, it is |
| 37 | + // a local variable, though in a realistic program it might not be |
| 38 | + Connection conn = null; |
| 39 | + |
| 40 | + // Connect to the database or fail |
| 41 | + System.out.print("Connecting to " + ip + ":" + port); |
| 42 | + try { |
| 43 | + // Open a connection, fail if we cannot get one |
| 44 | + conn = DriverManager.getConnection("jdbc:postgresql://" + ip + ":" + port + "/", user, pass); |
| 45 | + if (conn == null) { |
| 46 | + System.out.println("\n\tError: DriverManager.getConnection() returned a null object"); |
| 47 | + return; |
| 48 | + } |
| 49 | + } catch (SQLException e) { |
| 50 | + System.out.println("\n\tError: DriverManager.getConnection() threw a SQLException"); |
| 51 | + e.printStackTrace(); |
| 52 | + return; |
| 53 | + } |
| 54 | + System.out.println(" ... successfully connected"); |
| 55 | + |
| 56 | + System.out.print("Disconnecting from database"); |
| 57 | + try { |
| 58 | + conn.close(); |
| 59 | + } catch (SQLException e) { |
| 60 | + System.out.println("\n\tError: close() threw a SQLException"); |
| 61 | + e.printStackTrace(); |
| 62 | + return; |
| 63 | + } |
| 64 | + System.out.println(" ... connection successfully closed"); |
12 | 65 | } |
13 | 66 | } |
0 commit comments