JDBC Connectivity

You can not do everything in RAM. You need persistence.


Persistence can be achieved by writing to files or using Serilization too but Database is a more flexible way. Some of my friends are searching a way to connect to DB. This post is dedicated to them.

 I am assuming that the DB is Oracle. Following is a program to connect to a DB. Unfortunately I don't have a DB installed. So could not test it either but this will run accordingly with your DB.

1. Get the driver from http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html
2. Add this jar to your program classpath
3. Get the database parameters such as, database host, database port, database service name, database user name, database password
4. Edit the following program with required details as I mentioned in point 2


 import java.io.IOException;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 /**  
  *   
  */  
 /**  
  * @author Palash  
  *   
  */  
 public class MySecondProgram {  
      /**  
       * @param args  
       * @throws ClassNotFoundException  
       * @throws SQLException  
       * @throws IOException  
       */  
      public static void main(String[] args) throws ClassNotFoundException,  
                SQLException {  
           // Loads the driver and register it.  
           Class.forName("oracle.jdbc.driver.OracleDriver");  
           // Gets the connection  
           Connection conn = DriverManager.getConnection(  
                     "jdbc:oracle:thin:@DB_HOST:DB_PORT:DB_SERVICE_NAME",  
                     "USER_NAME", "PASSWORD");  
           // Prepare a statement to run on the connection  
           PreparedStatement statement = conn  
                     .prepareStatement("SELECT 'a' FROM DUAL");  
           // Run the qury in DB and get results  
           ResultSet rs = statement.executeQuery();  
           // Now, extract data from result set  
           while (rs.next()) {  
                String data = rs.getString(0);  
                System.out.println(data);  
           }  
      }  
 }  

5. Compile and run it.

Hope this helps you out.
Don't just stop here, if this article helped you out, spread the word.
Next
Palash Kanti Kundu

No comments:

Post a Comment