JDBC Sample Code

A working example that connects to the csc Oracle database using JDBC, runs a query, and displays results in one java class.
package schumeyer;

import java.io.*;
import java.sql.*;

import oracle.jdbc.pool.OracleDataSource;

public class VerySimpleEx {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        Connection conn=null;
        
        try {
            // read the username and password from a file
            File file = new File("N:/db.txt");
            BufferedReader in = new BufferedReader(new FileReader(file));
            String username = in.readLine();
            String password = in.readLine();
            in.close();
            
            // open a connection
            OracleDataSource ods = new OracleDataSource();
            ods.setUser(username);
            ods.setPassword(password);
            ods.setURL(
"jdbc:oracle:thin:@csdb.csc.villanova.edu:1521:csdb");
            conn = ods.getConnection();
            
            // list all aircraft
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(
                    "SELECT aid,aname,cruisingrange " +
                    "FROM aircraft " +
                    "ORDER BY aid");
            while (rs.next()) {
                System.out.printf("%2d %30s %5d\n",
                        rs.getInt(1), rs.getString(2), rs.getInt(3));
            }
            rs.close();
            st.close();
    
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (conn != null)
                    conn.close();
                System.out.printf("Closed connection.\n");
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }            
        }
    }        
    
}