JDBC connection to an Oracle Database
A student emailed me asking me how to connect to Oracle Database from within a Java Program.
The following is a simple complete example
package model;
import java.sql.*;
import oracle.jdbc.OracleDriver;
public class Class1 {
public Class1() {
try
{
String username = "scott"; // standard usename and password for SCOTT tiger USER
String password = "tiger";
String thinConn = "jdbc:oracle:thin:@localhost:1521:ORCL";
//The above line defines the connection string of the target database.
// It is important to specify the correct one,, it has the format
// jdbc:oracle:thin@server_address:listener_port:Oracle_instance_SID
// The first part before @ sign is fixed,, however you may need to change the other part according to you env.
// Server_address is the IP address or server name of the host computer that is running Oracel
// if you are running Oracle on your machine you can use either localhost or 127.0.0.1
// Listner_Port : If the TCP/IP port number that the Oracle listener is using typically 1521
// Instance_ID : Each Oracle installation creates an Instance and and identifier is given to this instance
// If you installed Oracle and used default setting, it is most probably ORCL
// you can find out this value by logging as SYS or SYSTEM user and run the following query
// SELECT * FROM V$INSTANCE and look for the instance name columm
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(thinConn,username,password);
conn.setAutoCommit(false);
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery ( "select * from EMPLOYEES"); // The SQL statement
while (rset.next ())
System.out.println( rset.getString (2)); //print the second field
conn.close();
// return conn;
}
catch (
SQLException x)
{System.out.println("SQL Error");}
}
public static void main(String[] args) {
Class1 class1 = new Class1();
}
}