JDBC Java Database Connectivity 1 JDBC JDBC stands
JDBC – Java Database Connectivity 1
JDBC • JDBC stands for "Java Data. Base Connectivity". • JDBC™ is an API developed by Sun Microsystems that provides a standard way to access data using the Java™ programming language. • Using JDBC, an application can access a variety of databases and run on any platform with a Java Virtual Machine. • It isn't necessary to write separate applications to access different database systems (Oracle and Sybase, for example). • Using JDBC allows you to write one application that can send SQL statements to different database systems.
JDBC • The JDBC API defines a set of Java interfaces that encapsulate major database functionality, such as - running queries, - processing results, and - determining configuration information. • Because JDBC applications are written in Java, applications work on any platform.
How JDBC Works • Establish a connection with a data source • Send queries and update statements to the data source • Process the results
How JDBC Works • The Java application calls JDBC classes and interfaces to submit SQL statements and retrieve results. • The JDBC API is implemented through the JDBC driver. • The JDBC Driver is a set of classes that implement the JDBC interfaces to process JDBC calls and return result sets to a Java application. • The database (or data store) stores the data retrieved by the application using the JDBC Driver.
JDBC Architecture Oracle Driver Oracle Java Application JDBC DB 2 Driver Network DB 2 My. SQL Driver My. SQL 7
JDBC Architecture (cont. ) Application JDBC Driver • Java code calls JDBC library • JDBC loads a driver • Driver talks to a particular database • An application can work with several databases by using all corresponding drivers • Ideal: can change database engines without changing any application code.
JDBC API • Data. Source Object • Connection Object • Statement/Prepared. Statement/Callable. Statement Object • Result set Object
JDBC API • A Data. Source object is used to establish connections. - Driver Manager can also be used to establish a connection, connecting through a Data. Source object is the preferred method. • A Connection object controls the connection to the database. - An application can alter the behavior of a connection by invoking the methods associated with this object. - An application uses the connection object to create statements.
JDBC API • Statement, Prepared. Statement, and Callable. Statement objects are used for executing SQL statements. - A Prepared. Statement object is used when an application plans to reuse a statement multiple times. - The application prepares the SQL it plans to use. Once prepared, the application can specify values for parameters in the prepared SQL statement. The statement can be executed multiple times with different parameter values specified for each execution. - A Callable. Statement is used to call stored procedures that return values. - The Callable. Statement has methods for retrieving the return values of the stored procedure.
JDBC API • A Result. Set object contains the results of a query. - A Result. Set is returned to an application when a SQL query is executed by a statement object. - The Result. Set object provides methods for iterating through the results of the query.
Why JDBC? • ODBC (Open Database Connectivity) is an established standard API for database access. • ODBC isn't appropriate for direct use from the Java programming language because it uses a C interface. • The JDBC API was modeled after ODBC, but, because JDBC is a Java API, it offers a natural Java interface for working with SQL. • JDBC is needed to provide a "pure Java" solution for application development.
JDBC API • The JDBC API is available in the java. sql and javax. sql packages. • Driver. Manager - Loads JDBC drivers in memory. Can also be used to open connections to a data source. • Connection - Represents a connection with a data source. It is also used for creating Statement, Prepared. Statement and Callable. Statement objects.
JDBC API • Statement - Represents a static SQL statement. Can be used to retrieve Result. Set object/s. • Prepared. Statement - Higher performance alternative to Statement object, represents a precompiled SQL statement. • Callable. Statement - Represents a stored procedure. Can be used to execute stored procedures in a RDBMS which supports them. • Result. Set - Represents a database result set generated by using a SELECT SQL statement. • SQLException - An exception class which encapsulates database access errors.
JDBC Driver Types • JDBC drivers are divided into four types or levels. • Type 1: JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native) Type 3: All. Java/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver • JDBC-ODBC Bridge driver • The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. • ODBC is a generic API. • The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available
Type 1 JDBC Driver • Functions: • Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. • Sun provides a JDBC-ODBC Bridge driver. sun. jdbc. odbc. Jdbc. Odbc. Driver. This driver is native code and not Java. • There is some overhead associated with the translation work to go from JDBC to ODBC.
Type 1 JDBC Driver Advantage • The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Disadvantages 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. 2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types. 3. The client system requires the ODBC Installation to use the driver. 4. Not good for the Web.
Type 2 JDBC Driver • Native-API/partly Java driver • The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i. e. this driver is specific to a particular database. • Some distinctive characteristic of type 2 jdbc drivers are shown below. • Example: Oracle will have oracle native api.
Type 2 JDBC Driver Functions: • This type of driver converts JDBC calls into calls to the client API for that database
Type 2 JDBC Driver Advantage • The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also it uses Native api which is Database specific. Disadvantage • 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. 2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue. 3. If we change the Database we have to change the native api as it is specific to a database 4. Usually not thread safe.
Type 3 JDBC Driver • All Java/Net-protocol driver • Type 3 database requests are passed through the network to the middle-tier server. • The middle-tier then translates the request to the database.
Type -3 JDBC Driver Functions: • Follows a three tier communication approach. • Can interface to multiple databases - Not vendor specific. • The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database. • Thus the client driver to middleware communication is database independent
Type 3 JDBC Driver Advantage • 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines. 2. This driver is fully written in Java and hence Portable. It is suitable for the web. 3. There are many opportunities to optimize portability, performance, and scalability. 4. The net protocol can be designed to make the client JDBC driver very small and fast to load. 5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. 6. This driver is very flexible allows access to multiple databases using one driver. 7. They are the most efficient amongst all driver types. Disadvantage • It requires another server application to install and maintain. • Traversing the recordset may take longer, since the data comes through the backend server.
Type 4 JDBC Driver • Native-protocol/all-Java driver • The Type 4 uses java networking libraries to communicate directly with the database server.
Type 4 JDBC Driver Functions • Type 4 drivers are entirely written in Java that communicate directly with a vendor's database through socket connections. • No translation or middleware layers, are required, improving performance. • The driver converts JDBC calls into the vendorspecific database protocol so that client applications can communicate directly with the database server. • Completely implemented in Java to achieve platform independence. • e. g include the widely used Oracle thin driver - oracle. jdbc. driver. Oracle. Driver which connect to jdbc: oracle: thin URL format.
Type 4 JDBC Driver Advantage • 1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web. 2. Number of translation layers is very less i. e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. 3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Disadvantage With type 4 drivers, the user needs a different driver for each database
CRUD OPERATIONS • CRUD stands for create, read, update, delete. • Create statement in SQL looks like – Create table mytab ( mynum number , name varchar 2(25)); • READ statement looks like – Select * from mytab where mynum=25; • UPDATE statement looks as – Update mytab set mynum=88 where mynum=25; • DELETE statement like – Delete from mytab where mynum=88;
DDL – DML – DCL - TCL • DDL – Data Definition Language – These queries are used to create database objects such as tables, indexes, procedures, constraints – Create , drop, alter, truncate, comment, rename • DML – Data Manipulation Language – These queries are used to manipulate the data in the database tables. – Insert, update, delete, select (more available) • DCL – Data Control Language – These are data control queries like grant and revoke permissions • TCL– Transaction Control Language – These are transaction control queries like commit, revoke, savepoint, set transaction
EXERCISE • Create tables using primary key • Using Foreign key relationship. • Select Query with where clause • Select Query with group by , having and order by clauses • Insert , Update and Delete operations. 31
CRUD and Java • Java can invoke CRUD operations using JDBC • JDBC is Java Database Connectivity and there are 4 types of drivers which form a bridge between java and a database • The Operations communicated by java will be translated in a form understood by the database by the drivers.
JDBC Drivers • Type 1 Driver - JDBC-ODBC bridge – This is an ODBC driver, which is open source • Type 2 Driver – Native API driver – This is more like the OCI (Oracle Call Interface) call interface is converted to native calls of the database. • Type 3 Driver – Network protocol driver – This is achieved by using a Java Driver in a middleware • Type 4 Driver – Native Protocol Driver – This is a driver written purely in Java Language • We Usually prefer to depend on the Type 4 driver
Seven Steps • Load the driver • Define the connection URL • Establish the connection • Create a Statement object • Execute a query using the Statement • Process the result • Close the connection 34
Loading the Driver • We can register the driver indirectly using the statement Class. for. Name("com. mysql. jdbc. Driver"); • Class. for. Name loads the specified class • When mysql. Driver is loaded, it automatically - creates an instance of itself - registers this instance with the Driver. Manager • Hence, the driver class can be given as an argument of the application 35
DRIVERS • ORACLE DRIVER –ojdbc 6. jar or higher versions (classes 12. jar) • http: //www. java 2 s. com/Code/Jar/o/ojdbc 6. htm • MYSQL DRIVER –com. mysql. jdbc_5. 1. 5. jar • http: //www. java 2 s. com/Code/Jar/c/Downloadco mmysqljdbc 515 jar. htm 36
An Example //A driver for My. SQL database Class. for. Name("com. mysql. jdbc. Driver"); // A Driver for ORACLE database Class. for. Name(" oracle. jdbc. driver. Oracle. Driver "); // A Driver for NETBEANS DERBY database Class. for. Name("org. apache. derby. jdbc. Client. Driver"); 37
Connecting to the Database • Every database is identified by a URL • Given a URL, Driver. Manager looks for the driver that can talk to the corresponding database • Driver. Manager tries all registered drivers, until a suitable one is found 38
Connecting to the Database SYNTAX: Connection con = Driver. Manager. get. Connection(“URL”, ”username”, ”password”); Example – Establishing connection with ORACLE Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @local host: 1521: XE", “scott", “tiger"); 39
Database URL 40
Example – Establishing connection with MYSQL Connection con=Driver. Manager. get. Connection( "jdbc: mysql: //localhost: 3306/mysqldb", "root"); 41
Establishing connection with NETBEANS DERBY Data base Class. for. Name("org. apache. derby. jdbc. Client. Drive r"); Connection con=Driver. Manager. get. Connection( jdbc: derby: //localhost: 1527/DBNAME", “USERNA ME", “PASSWORD"); Note : DBNAME, USERNAME, PASSWORD values needs to be identified from your system. 42
Interaction with the Database • We use Statement objects in order to - Query the database - Update the database • Three different interfaces are used: Statement, Prepared. Statement, Callable. Statement • All are interfaces, hence cannot be instantiated • They are created by the Connection
Using Statement Object Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @l ocalhost: 1521: XE", “scott", “tiger"); stmt = con. create. Statement(); String sql = "INSERT INTO DEPT VALUES (50, ‘MARKETING', ‘MUMBAI’)"; stmt. execute. Update(sql); 44
Using Prepared. Statement • Assume EMP table with columns empid, ename Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @localho st: 1521: XE", “scott", “tiger"); Prepared. Statement stmt=con. prepare. Statement("insert into Emp values(? , ? )"); stmt. set. Int(1, 101); stmt. set. String(2, "Ratan"); int i=stmt. execute. Update(); System. out. println(i+" records inserted"); 45
Statement and Prepared Statement • A Statement Interface is used to create a statement i. e. a query to be executed against a database. In this process, two calls are made to the database system , one to get the table metadata and other to get the data itself. The statement object is also compiled every time it executes. • A Prepared statement comes in handy as it is compiled and cached and only makes on database call when invoked. The compilation would be skipped even if the values in the where clause change
About Prepared Statements • Prepared Statements are used for queries that are executed many times • They are parsed (compiled) by the DBMS only once • Column values can be set after compilation • Instead of values, use ‘? ’ • Hence, Prepared Statements can be though of as statements that contain placeholders to be substituted later with actual values 47
execute. Update() method int execute. Update (String sql) Creates a Statement object for sending SQL statements to the database. Returns either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing
Inserting a Row – Example using Statement Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @localhost: 152 1: XE", “scott", “tiger"); Statement stmt = con. create. Statement(); int i= stmt. execute. Update(“INSERT INTO pet VALUES(12, ’minou’, ’Gwen’, ’cat’)”);
Insert record –using Prepared Statement Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @localhost: 152 1: XE", “scott", “tiger"); String query = "insert into dept(deptnum, deptname, deptloc) values(? , ? )"; pstmt = con. prepare. Statement(query); pstmt. set. Int(1, 10); pstmt. set. String(2, “SALES"); pstmt. set. String(3, “LONDON"); pstmt. execute. Update(); 50
UPDATE Statement • Assume DBUSER Table with columns (USERNAME & USER_ID) Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @localhost: 152 1: XE", “scott", “tiger"); String qry = "UPDATE DBUSER SET USERNAME = ? WHERE USER_ID = ? "; Prepared. Statement ps = con. prepare. Statement(qry); ps. set. String(1, “newadmin"); ps. set. Int(2, 1001); ps. execute. Update(); 51
DELETE Statement Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: @local host: 1521: XE", “scott", “tiger"); String qry = "DELETE DBUSER WHERE USER_ID = ? "; Prepared. Statement ps = con. prepare. Statement(qry); ps. set. Int(1, 1001); ps. execute. Update(); 52
Example • Assume MYUSERS table with columns (USERID (NUMBER), USERNAME (VARCAHR 2(20)) Class. for. Name("oracle. jdbc. driver. Oracle. Driver"); Connection con=Driver. Manager. get. Connection("jdbc: oracle: thin: @localhost: 1521: XE", “scott", “tiger"); Prepared. Statement ps=con. prepare. Statement("insert into MYUSERS values(? , ? )"); ps. set. Int(1, 1001); ps. set. String(2, “ADMIN"); int a=ps. execute. Update(); 53