One Liner...

...tujhe bhi apne pe ye aeitbaar hai ki nahi...

Tuesday, December 20, 2011

Simple JDBC Program

The basic process for a single data retrieval operation using JDBC would be as follows.
1. a JDBC driver would be loaded;
2. a database Connection object would be created from using the DriverManager (using the database driver loaded in the first step);
3. a Statement object would be created using the Connection object;
4. a SQL Select statement would be executed using the Statement object, and a ResultSet would be returned;
5. the ResultSet would be used to step through (or iterate through) the rows returned and examine the data.

import java.sql.*;

public class SimpleJdbcProgram {

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.OracleDriver");//TODO : find out Class.forName

//        DriverManager is used to load a JDBC Driver. A Driver
//        is a software vendor's implementation of the JDBC API. After a
//        driver is loaded, DriverManager is used to get a Connection.
//        In turn, a Connection is used to create a Statement,
//        or to create and prepare a PreparedStatement or    CallableStatement.
//        Statement and PreparedStatement objects are used to execute
//        SQL statements. CallableStatement objects are used to execute
//        stored procedures.
    Connection conn = DriverManager.getConnection(
    "jdbc:oracle:thin:@//localhost:1521/ORADBA", "scott", "tiger");
// @//machineName:port/SID, userid, password : works fine if tnsnames.ora is fine.
//{host:port:sid | net_service_name | connect_descriptor}
    try {
//            Creates a Statement object for sending SQL statements
//            to the database. SQL statements without parameters are
//            normally executed using Statement objects. If the same
//            SQL statement is executed many times, it may be more
//            efficient to use a PreparedStatement object.
        Statement stmt = conn.createStatement();
        try {
            ResultSet rset = stmt.executeQuery("select ename from emp");
            try {
                while (rset.next())
                    System.out.println(rset.getString(1)); // Print col 1
            } finally {
            try {
                rset.close();
            } catch (Exception ignore) {
            }
        }
        } finally {
            try {
                stmt.close();
                } catch (Exception ignore) {
                }
            }
            } finally {
                try {
                    conn.close();
                } catch (Exception ignore) {
                }
            }
        }
    }

No comments:

Post a Comment