Presentation is loading. Please wait.

Presentation is loading. Please wait.

JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.

Similar presentations


Presentation on theme: "JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable."— Presentation transcript:

1 JDBC

2 Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable the primary functions of opening and managing connections to a particular DBMS. The java.sql package contains the entire JDBC API that sends SQL (Structured Query Language) statements to relational databases and retrieves the results of executing those SQL statements. Important classes and interfaces of this package are: 1. DriverManager Class 2. Connection Interface 3. Statement Interface 4. PreparedStatement Interface 5. ResultSet Interface 6. ResultSetMetaData Interface

3 1. DriverManager Class It controls the interface between the application and a set of JDBC drivers. Provides set of methods for managing the drivers. Used to locate a suitable driver from amongst those loaded on the computer Methods – public static java.sql.Connection getConnection (String url, String user, String password) – it attempts to establish a connection to the specified database URL. If it is successful, it returns a Connection object, which represents a connection to the database. 2. Connection Interface A Connection object represents a connection with a database. In this SQL statements can be executed, returning resultsets. Methods – public abstract void close () - it provides for immediate release of the Connection’s database resource and JDBC resources. public abstract Statement createStatement () - it returns a new statement object that can be used to execute SQL statements.

4 3.Statement Interface The Statement object execute SQL statements that are static and obtain results following execution. Results are in the form of a ResultSet object. Methods- public abstract ResultSet executeQuery (String sql) – executes an SQL statement that returns a single ResultSet object. public abstract int executeUpdate (String sql) - executes SQL UPDATE, DELETE OR INSERT statements and return a row count. 4.PreparedStatement Interface It extends the Statement interface. If the application requires multiple execution of a particular SQL statement, it is pre-complied and stored in PreparedStatement object. This object can then be used many times to execute the statement efficiently. Methods – public abstract ResultSet executeQuery () – used to execute SQL statements. public abstract int executeUpdate () - executes SQL UPDATE, DELETE OR INSERT statements and do not return anything.

5 5. ResultSet Interface The data that is generated by the execution of a SQL statement is stored in, and can be accessed from a ResultSet object. It watches a single row of data at a time. This row of data is called its current row. When a SQL statement is re-executed the current ResultSet is automatically closed and a new RecordSet is created. Methods- public abstract void close () – is used when the application wants to release a ResultSet database resource and JDBC resource immediately public abstract String getString (String columnName) – gets the value of a column in the current row as Java String public abstract boolean next () – A ResultSet is initially positioned before its first row, the first call to the next makes the first row the current row, second call makes the second row the current row etc.

6 6. ResultSetMetaData Interface The ResultSetMetaData object returned by getMetaData() constructor provides access to information which indicates the number, type and properties of ResultSet columns. Methods – public abstract int getColumnCount () – method returns the number of columns in the ResultSet public abstract String getColumnName (int column) – method returns the name of the column public abstract String getTableName (int column) – returns the name of a table.

7 Java Database Connectivity Steps Before you can create a java jdbc connection to the database, you must first import the java.sql package. Following are steps that must be followed to establish a JDBC connection:- 1. Loading Driver 2. Establishing Connection 3. Creating a JDBC Statement object 4. Executing Statements and getting Results 5. Closing Database Connection

8 Loading a Driver It is necessary to load the JDBC drivers before attempting to connect to the database. In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. This method dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows user to make the driver registration configurable and portable. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. The following example uses Class.forName( ) to register the Oracle driver: try { Class.forName ("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException ex) { System.out.println ("Error: unable to load driver class!"); }

9 Establishing Connection The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. try { Connection dbConnection=DriverManager.getConnection (url,”loginName”,”Password”) ; } catch( SQLException x ) { System.out.println( “Couldn’t get connection!” ); }

10 Creating a JDBC Statement object Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, user need to instantiate a Statement object from connection object by using the createStatement() method. Example : Statement statement = dbConnection.createStatement(); A statement object is used to send and execute SQL statements to a database. Three kinds of Statements 1. Statement: Execute simple sql queries without parameters. Statement createStatement()- Creates an SQL Statement object. 2.Prepared Statement: Execute precompiled sql queries with or without parameters. PreparedStatement prepareStatement(String sql)- returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements. 3.Callable Statement: Execute a call to a database stored procedure. CallableStatement prepareCall(String sql)- returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements

11 Executing Statements Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements: executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate(). ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.

12 Closing JDBC connections At the end of your JDBC program, it is required explicitly close all the connections to the database to end each database session. However, if you forget, Java's garbage collector will close the connection when it cleans up stale objects. Relying on garbage collection, especially in database programming, is very poor programming practice. To ensure that a connection is closed, user could provide a finally block in code. A finally block always executes, regardless if an exception occurs or not. To close above opened connection you should call close() method as follows: dbconnection.close();

13 Connectivity Model Java Application The user Interface 32-bit ODBC Access Driver The Access Database and Its Table Java’s Driver Manager, Responsible for setting up the JDBC-ODBC bridge

14 Using Java’s Driver Manager to Connect to the Database Java Driver Manger ODBC System DSN The Access Database, table, With data in it. Creates a Connection Object, which communicates with the ODBC driver and in turn spawns a ResultSet object to hold the record set returned by the query made to the database table. The ResultSet Object This holds the records retrieved from the Access Database table

15 Navigating through Multiple Rows retrieved from a Database ResultSets are composed of rows of data. The table rows are retrieved in sequence. Intially, A ResultSet maintains a cursor pointing to it first row of data. The ResultSet.next() method is used to successively step through the rows of the tabular results. It returns false, when there are no more rows to navigate to in the ResultSet. Example- ResultSet rs = statement.executeQuery(“SELECT * from emp”); rs.next(); Extraction of values from the current row is possible in two ways: 1. Accessing columns of the current row by index number 2. Accessing columns of the current row by name.

16 Methods used to retrieve values from database The current row’s content are accessible via getXxx() method of the ResultSet Interface. Some of these methods are :- public abstract boolean getBoolean (String columnName) public abstract boolean getBoolean (int columnIndex) public abstract boolean getFloat (String columnName) public abstract boolean getFloat (int columnIndex) public abstract boolean getDouble (String columnName) public abstract boolean getDouble (int columnIndex) public abstract boolean getInt (String columnName) public abstract boolean getInt (int columnIndex) public abstract boolean getLong(String columnName) public abstract boolean getLong(int columnIndex) public abstract boolean getString(String columnName) public abstract boolean getString(int columnIndex)

17 import java.sql.*; public class jdbcodbc { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:odbc:java"; String db = "student"; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection(url) ; System.out.println("connection ok"); st = con.createStatement(); String sql = "select * from stud";

18 rs = st.executeQuery(sql); System.out.println("Id\tName\tMarks"); while (rs.next()) { System.out.print(rs.getInt(1)); System.out.print("\t "+rs.getString(2)); System.out.print("\t "+rs.getInt(3)); System.out.print("\t "+rs.getInt(4)); System.out.println("\t "+rs.getInt(5)); } rs.close(); st.close(); con.close(); } catch (Exception e) { System.out.println(e); } }

19 Popular JDBC driver names and database URL RDBMS JDBC driver nameURL format MySQLcom.mysql.jdbc.Driverjdbc:mysql://hostname/ databaseName ORACLE oracle.jdbc.driver.OracleDriverdbc:oracle:thin:@hostname:port Number:databaseName DB2COM.ibm.db2.jdbc.net.DB2Driverjdbc:db2:hostname:port Number/databaseName


Download ppt "JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable."

Similar presentations


Ads by Google