Take the 2-minute tour ×

Hi Below is the code I wrote for connecting to Oracle DB using JDBC connection and return some values. But this code establish the connection and returns the result if I am opening the oracle toad in my machine.

But when the oracle toad is closed and try to run this code, it will not connect.

Please let me knwo how to connect to oracle DB with out opening the oracle toad manually.

package library;
import java.io.IOException;
import java.sql.*;

public class DBAutomationConnection {
public static void main(String args[]) throws ClassNotFoundException, IOException, SQLException {
  DBAutomationConnection dbconn = new DBAutomationConnection();
  //Connection conn = dbconn.DBConnection1();
  dbconn.DBConnection1("select * from employee where empid='test123'","ROLE_NAME");


public void DBConnection1(String query, String colName)throws IOException, ClassNotFoundException{
 Connection connection = null;
 Statement stmt = null;
  try {
      // Load the JDBC driver

      String driverName = "oracle.jdbc.driver.OracleDriver";


      connection = DriverManager.getConnection("jdbc:oracle:thin:@//testhostname:1528/ServiceName", "XXAAA_U", "Jw9S");
      System.out.println("Connection successful: " +connection);

      try {
              stmt = connection.createStatement();
              ResultSet rs = stmt.executeQuery(query);
              while (rs.next()) {
                    //String UserID = rs.getString("USER_ID");
                  String UserID = rs.getString(colName);
        } catch (SQLException e ) {
              System.out.println("Could not execute query.");
        } finally {
              if (stmt != null) { stmt.close(); }

  } catch (SQLException e) {
                  System.out.println("Could not connect to the database");

share|improve this question

3 Answers 3

You should initialize Oracle TNS-Listener Service from your OS settings>services. You may need to check your tns configuration.

share|improve this answer

you need to install ORACLE client in your system to connect oracle remotely.


share|improve this answer

Do you have Oracle Thin driver installed in your system? This link can guide you.

share|improve this answer

Your Answer


