D:\work\db\src\Example1.java
1     
2    import java.sql.Connection; 
3    import java.sql.DriverManager; 
4    import java.sql.SQLException; 
5     
6    /** 
7     * This is a simple example that demostrates how to open a database 
8     * connection before we are trying to execute SQL statements, and 
9     * close a database connection when we are done. You can build your 
10    * code using this example as a skeleton. 
11    */ 
12   public class Example1 { 
13       public static void main(String args[]) { 
14           Example1 example = new Example1(); 
15           example.run(); 
16       } 
17    
18       /** 
19        * This is the skeleton code of database access 
20        */ 
21       public void run() { 
22           Connection con = null; 
23           try { 
24               con = openConnection(); 
25           } catch (SQLException e) { 
26               System.err.println("Errors occurs when communicating with the database server: " + e.getMessage()); 
27           } catch (ClassNotFoundException e) { 
28               System.err.println("Cannot find the database driver"); 
29           } finally { 
30               // Never forget to close database connection 
31               closeConnection(con); 
32           } 
33       } 
34    
35       /** 
36        * 
37        * @return a database connection 
38        * @throws SQLException when there is an error when trying to connect database 
39        * @throws ClassNotFoundException when the database driver is not found. 
40        */ 
41       private Connection openConnection() throws SQLException, ClassNotFoundException { 
42           // Load the Oracle database driver 
43           DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); 
44    
45           /* 
46           Here is the information needed when connecting to a database 
47           server. These values are now hard-coded in the program. In 
48           general, they should be stored in some configuration file and 
49           read at run time. 
50           */ 
51           String host = "shams.usc.edu"; 
52           String port = "1521"; 
53           String dbName = "cs585"; 
54           String userName = "temp"; 
55           String password = "temp585"; 
56    
57           // Construct the JDBC URL 
58           String dbURL = "jdbc:oracle:thin:@" + host + ":" + port + ":" + dbName; 
59           return DriverManager.getConnection(dbURL, userName, password); 
60       } 
61    
62       /** 
63        * Close the database connection 
64        * @param con 
65        */ 
66       private void closeConnection(Connection con) { 
67           try { 
68               con.close(); 
69           } catch (SQLException e) { 
70               System.err.println("Cannot close connection: " + e.getMessage()); 
71           } 
72       } 
73   }