Last active
August 29, 2015 14:17
-
-
Save magwas/fe305050c035bd7f0cb5 to your computer and use it in GitHub Desktop.
Simple command line app to test jdbc connectivity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//STEP 1. Import required packages | |
import java.sql.*; | |
public class JdbcQuery { | |
// JDBC driver name and database URL | |
static final String JDBC_DRIVER = "org.postgresql.Driver"; | |
public static void main(String[] args) { | |
if(args.length != 2) { | |
System.err.printf("usage: java [java opts] -cp <classpath containing jdbc driver and JdbcQuery> JdbcQuery <connection string> <sql>\n"); | |
System.exit(1); | |
} | |
Connection conn = null; | |
Statement stmt = null; | |
String db_url = args[0]; | |
String sql = args[1]; | |
try{ | |
//STEP 2: Register JDBC driver | |
Class.forName(JDBC_DRIVER); | |
//STEP 3: Open a connection | |
System.out.println("Connecting to database..."); | |
//conn = DriverManager.getConnection(DB_URL,USER,PASS); | |
System.out.printf("db url=%s\n",db_url); | |
conn = DriverManager.getConnection(db_url); | |
//STEP 4: Execute a query | |
System.out.println("Creating statement..."); | |
stmt = conn.createStatement(); | |
ResultSet rs = stmt.executeQuery(sql); | |
//STEP 5: Extract data from result set | |
ResultSetMetaData metadata = rs.getMetaData(); | |
int columnCount = metadata.getColumnCount(); | |
while (rs.next()) { | |
String row = ""; | |
for (int i = 1; i <= columnCount; i++) { | |
row += rs.getString(i) + ", "; | |
} | |
System.out.printf("%s\n",row); | |
} | |
//STEP 6: Clean-up environment | |
rs.close(); | |
stmt.close(); | |
conn.close(); | |
}catch(SQLException se){ | |
//Handle errors for JDBC | |
se.printStackTrace(); | |
}catch(Exception e){ | |
//Handle errors for Class.forName | |
e.printStackTrace(); | |
}finally{ | |
//finally block used to close resources | |
try{ | |
if(stmt!=null) | |
stmt.close(); | |
}catch(SQLException se2){ | |
}// nothing we can do | |
try{ | |
if(conn!=null) | |
conn.close(); | |
}catch(SQLException se){ | |
se.printStackTrace(); | |
}//end finally try | |
}//end try | |
System.out.println("Goodbye!"); | |
}//end main | |
}//end FirstExample |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used to figure out the java properties and jdbc uri and test the keystore in this:
javac JdbcQuery.java ;java -Djavax.net.ssl.keyStore=/home/mag/.keystore -Djavax.net.ssl.keyStorePassword=* -Djavax.net.ssl.trustStore=/home/mag/.keystore -Djavax.net.ssl.trustStorePassword=** -classpath /usr/share/java/postgresql-jdbc3.jar:. JdbcQuery "jdbc:postgresql://db.host.name/dbname?user=dbuser&ssl=true" "select * from pg_user"