Java – JDBC example program

I had one usecase and for which I wrote this program. This program is compatible with JRE1.7.

The program makes a database connection using JDBC for oracle database and for every 200 milliseconds, it queries the database table for data. After 15 secs, the program exits.

TimerTask class used for running the sql query for every 200 milliseconds.

import java.sql.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;


public class OracleDBConnection extends TimerTask {
   Connection conn = null;
   Timer timer = null;
   Statement stmt = null;
   ResultSet rs = null;
   int count = 0;
   int period = 200; // interval period
   int iteration = 1;

   int duration = 15000; // duration in milliseconds

   public OracleDBConnection(Connection p_connection, Timer p_timer) {
       conn = p_connection;
       timer = p_timer;
   }

   public void run() {
      System.out.println("Code executed every 200 milliseconds : " + iteration);
      try {
         // Execute a SQL query using the existing connection
         stmt = conn.createStatement();
         rs = stmt.executeQuery("select * from <table> fetch first 2 rows only");

         // Process the query results
         while (rs.next()) {
            // Retrieve data from the query results
            String data = rs.getString("user_name");

           // Do something with the retrieved data
            System.out.println(data);
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         // Close the database resources
         try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
      iteration++;
      count++;
      if (count * period >= duration) {
         timer.cancel(); // stop the timer when duration is reached
         Date now = new Date();
         SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         formatter.setTimeZone(TimeZone.getDefault());
         String formattedDateTime = formatter.format(now);
         System.out.println("Completed DB query statements execution at time : " + formattedDateTime);
      }
   }
}

Main program that creates the connection and passes it to TimerTask object.

import java.util.TimeZone;
import java.text.SimpleDateFormat;

public class OracleDBConnectionTest {
    public static void main(String[] args) throws InterruptedException {
        Connection conn = null;
        String url = "jdbc:oracle:thin:@<connectionString>";
        String username = "username";
        String password = "password";

        try {

            Timer timer = new Timer();

            // Load the Oracle JDBC driver
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver()) ;

            // Connect to the Oracle database
            conn = DriverManager.getConnection(url, username, password);

            // Create a TimerTask to execute the OracleDBConnection every 10 seconds
            TimerTask task = new OracleDBConnection(conn, timer);

            // Get current date and time in local time zone
            Date now = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            formatter.setTimeZone(TimeZone.getDefault());
            String formattedDateTime = formatter.format(now);

            System.out.println("Starting DB Query Statements at time : " + formattedDateTime);

            timer.schedule(task, 0, 200);

            Thread.sleep(20000);

            now = new Date();
            formattedDateTime = formatter.format(now);

            System.out.println("Exiting main program at time : " + formattedDateTime);

        } catch (SQLException e) {
            e.printStackTrace();

        } finally {
            // Close the database connection
            try {
                if (conn != null) {
                    System.out.println("Closing the connection");
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Leave a comment