|
JDBC Simple ApplicationSimplest JDBC application consists of 2 parts:
Java Code (save in file JdbcExample.java): import java.sql.*; public class JdbcExample { static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver"; static final String DB_URL = "jdbc:oracle:thin:@localhost:11521:XE"; static final String USER = "system"; static final String PASS = "manager"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { // Register JDBC driver Class.forName(JDBC_DRIVER); // Open a connection System.out.println( String.format("\nConnecting to \ndatabase %s \nwith login=%s and \npassword=%s", DB_URL, USER, PASS) ); conn = DriverManager.getConnection(DB_URL,USER,PASS); // Execute a query stmt = conn.createStatement(); String sql = "SELECT name, updated_date FROM Account"; System.out.println("\n\nRunning sql: " + sql); ResultSet rs = stmt.executeQuery(sql); System.out.println("\n\nPrinting data"); // Extract data from result set int maxCount=10; while(rs.next() && maxCount-- > 0) { int pos=1; System.out.println ( rs.getObject(pos++).toString() + ", " + rs.getObject(pos++).toString() ); } // Clean-up the environment rs.close(); stmt.close(); conn.close(); System.out.println ("\nAll done, no exceptions\n"); } catch(Exception e) { e.printStackTrace(); } finally { try { if(stmt!=null) stmt.close(); } catch(SQLException e) { e.printStackTrace(); try { if (conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } } } } } The above can be run using the following two commands on the shell: javac JdbcExample.java java -cp ojdbc6.jar:. JdbcExample Note the usage of ojdbc6.jar file This jar file needs to be downloaded from the Internet (oracle.com is a good source for the same). |
Got a thought to share or found a
bug in the code?
We'd love to hear from you:
Name: | |
Email: | (Your email is not shared with anybody) |
Comment: |
Facebook comments: