Java: Connect to DB and fetch data

With the code below you can connect to an Oracle database using JDBC driver and fetch some data:

(you can find the libraries needed below)

import java.sql.*;
import java.util.Date;
import java.util.Properties;

public class ConnectToOracle {

static Driver driver;
static Connection conn = null;
static String driverUsed = "oracle.jdbc.driver.OracleDriver";

static String serverAddress = "jdbc:oracle:thin:nyusername/mypass@myIP:myPort:myDB";      

public static void makeConnection(String svr) {
//Properties props = new Properties();
//props.put("internal_logon", "sysdba");
try {
System.out.println("Loading ... " + driverUsed);
driver = (Driver) Class.forName(driverUsed).newInstance();
System.out.println("Connecting ... " + svr);
//conn = DriverManager.getConnection(svr, props);
conn = DriverManager.getConnection(svr);            
System.out.println("Ready.");
Date startDate = new Date();
Statement sqlStmt = conn.createStatement();
String theQuery;

theQuery = "select column_name, data_type " +
"from all_tab_columns " +
"where TABLE_NAME = 'S_SRV_REQ'";

System.out.println(theQuery);

ResultSet rSet = sqlStmt.executeQuery(theQuery);

int i=0;
while(rSet.next()){
System.out.println(rSet.getString("column_name"));               
i++;
}
System.out.println("\n--------------");
System.out.println(i + " records");
Date endDate = new Date();

System.out.println("in " + (endDate.getTime() - startDate.getTime()) + " milliseconds");
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
makeConnection(serverAddress);
}
}

 


 

jdbc classes (old version)

jdbc classes (new version)

 

Leave a Reply