Search This Blog

JAVA: JDBC connect to Oracle

import java.sql.*;
public class TestJDBC {

public static void main(String[] args) {

String host = "localhost";
String dbName = "orcl";
int port = 1521;
String oracleURL = "jdbc:oracle:thin:@" + host + ":" + port + ":" +dbName;
String username = "scott";
String password = "tiger";

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(oracleURL, username, password);
Statement s = connection.createStatement();
String query =
"SELECT empno, ename, job, sal from emp where rownum < 10";
ResultSet results = s.executeQuery(query);

while(results.next()) {
System.out.println(results.getString(1) + "---" +results.getString(2) + "---" +
results.getString(3) + "---" +results.getString(4));

}

connection.close();
}

catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: ");
}

catch (SQLException sqle) {
System.out.println("SQL Error ...........: ");

}

catch (Exception others) {
System.out.println("Error ........... others: " +others.getMessage());
}
}
}

No comments:

Post a Comment