Saturday, May 31, 2008

Role of JDBC in Java? What are JDBC components?


Role of JDBC in Java


JDBC is probably used to achieve the following three tasks in Java:-

  • Connect to data source - it helps the Java program to establish a connection to a data source, such as a database.
  • Sending/Executing SQL statements - once the connection gets established then JDBC can be used to prepare, send, and execute SQL queries or Update statements on the data source, the connection is established to.
  • Retrieving results and processing them - finally the JDBC APIs can be used to retrieve the results of the fired SQL statements and helps them getting processed to be used in the Java application.


Example:
//Connecting to the data source

Connection con = DriverManager.getConnection("url", "userid","password");

//preparing SQL statement

Statement stmt = con.createStatement();


//sending/executing SQL queries and retrieving the result

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


//processing the result

while (rs.next()) {

...

}


Components of JDBC

  • JDBC API - The JDBC 4.0 APIs come in two packages: java.sql and javax.sql and these packages contain all the APIs which provide programmatic access to a relational database (like Oracle, SQL Server, MySQL, etc.) from Java.
  • JDBC Driver Manager - There are two ways of connecting to a database - One, by using the DriverManager class (the traditional way of establishing connection to a database from Java) and Two, by using a Data Source. This method requires javax.naming and javax.sql packages to find a DataSource object registered with JNDI, and to establish connection using that DataSource object. This is the recommended approach of establishing connection to a database from Java.
  • JDBC Test Suite - this test suite will of course not be exhaustive, but they do contain almost all the standard test cases required to test the many JDBC features. You may only need to add the application specific test cases.
  • JDBC-ODBC Bridge - as the name suggests this enables JDBC access via ODBC drivers. Though this is normally used only for development and testing purposes and not for production use.



Share/Save/Bookmark


No comments: