Monday, June 8, 2009

Connecting to a Database via JDBC Architecture

JDBC

• It is an API Specification developed by Sun MicroSystems

• It is a Core part of the standard Java Platform.

• It defines a uniform interface for accessing different relational databases .

• It is included in the standard JDK.

Accessing a Database [ Connecting to a Database via JDBC Architecture ]

1. Register the JDBC driver with the DriverManager

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2. Establish a Database Connection using Database URL jdbc::

Connection con = DriverManager.getConnection("jdbc:odbc:dsname");

3. Execute an SQL Statement

i. Create a Statement object using Connection object's createStatement() method.

Statement stmt = con.createStatement();

ii. Query can be executed by using the Statement object's executeQuery()
method. It returns a ResultSet object that encapsulates the retrieved
data.

ResultSet rs = stmt.executeQuery("Query");

4. Process the Results

i. ResultSet object's next()& previous() methods can be used to
iterate through the rows of the result set.

ii. ResultSet object's getString() method is used to extract the value of
specified fields.


while(rs.next()){
System.out.println(rs.getString("fieldName"));
}

5. Close the Database Connection.

Database Connections should be closed after completing transactions.

rs.close();
stmt.close();
con.close();

[Written on: Monday, August 22, 2005 3:02:34 PM]

No comments: