Oracle JDBC Program
Steps to connect to Oracle Database using Java (JDBC)
Steps to connect to Oracle Database using Java (JDBC)
Download the Oracle JDBC driver ojdbc6.jar from
Go to eclipse and
Choose “ojdbc6.jar” and upload the file using above.
Create a java class as follows
-------------------------------------------------
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcOracleConnection {
public static void main(String[] args) {
Connection conn1 = null;
Statement statement = null;
try {
Class.forName("oracle.jdbc.OracleDriver");
String dbURL1 = "jdbc:oracle:thin:username/password@localhost:1521:XE";
conn1 = DriverManager.getConnection(dbURL1);
if (conn1 != null) {
System.out.println("Connected with connection #1");
}
statement = conn1.createStatement();
// Create a query to use.
String query = "select table_name, owner from dba_tables where rownum <=10";
ResultSet resultSet = statement.executeQuery(query);
System.out.println("Printing result...");
while (resultSet.next()) {
String tn = resultSet.getString("table_name");
String opg = resultSet.getString("owner");
System.out.println("\ttable_name: " + tn +", owner: " + opg );
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn1 != null && !conn1.isClosed()) {
conn1.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
-----------------------------------------------------
The sample output of class JdbcOracleConnection is as follows
No comments:
Post a Comment