• Save
Dacj 4 1-c
Upcoming SlideShare
Loading in...5
×
 

Dacj 4 1-c

on

  • 636 views

 

Statistics

Views

Total Views
636
Views on SlideShare
602
Embed Views
34

Actions

Likes
1
Downloads
0
Comments
0

1 Embed 34

http://niitcourseslides.blogspot.in 34

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Dacj 4 1-c Dacj 4 1-c Presentation Transcript

  • CollaborateKnowledge Byte In this section, you will learn about: • Working with Joins • JDBC API • Isolation Levels ©NIIT Collaborate Lesson 1C / Slide 1 of 33
  • CollaborateWorking with Joins • SQL joins in queries are executed using the Statement or PreparedStatement objects. • A join is an SQL operation that enables you to specify conditions to retrieve data from multiple tables. • Different types of joins that you can use in a Java application are: • Inner joins • Cross joins • Outer joins ©NIIT Collaborate Lesson 1C / Slide 2 of 33
  • CollaborateWorking with Joins (Contd.) • Inner Join: • Combines the rows retrieved from multiple tables on the basis of the common columns of the tables. • Specifies the condition to join the tables using comparison operators in the ON clause of the SELECT statement. • Can be created using the following code snippet in a java application: String str = "SELECT EmpInfo.EName, EmpInfo.DeptID, DeptInfo.DeptName, EmpInfo.EmpDesig FROM EmpInfo INNER JOIN DeptInfo ON EmpInfo.DeptID = DeptInfo.DeptID"; Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "administrator", ""); Statement stat = con.createStatement(); ResultSet rs = stat.executeQuery(str); ©NIIT Collaborate Lesson 1C / Slide 3 of 33
  • CollaborateWorking with Joins (Contd.) • Cross Join: • Includes more than one table without any condition in the ON clause. • Is also known as cartesian join. • Can be created using the following code snippet in a Java application: String str = "SELECT EmpID, EName, DeptName, EmpDesig FROM EmpInfo CROSS JOIN DeptInfo"; Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "administrator", ""); Statement stat = con.createStatement(); ResultSet rs = stat.executeQuery(str); ©NIIT Collaborate Lesson 1C / Slide 4 of 33
  • CollaborateWorking with Joins (Contd.) • Outer Join: • Retrieves all the rows from one table and the matching rows from another. • Eliminates the information contained in the row that does not match the condition for only one of the tables. • Is an extension of equi join. • Can be created using the following code snippet in a Java application: String str = "SELECT EmpInfo.EmpID, EmpInfo.EName, EmpInfo.DeptID, DeptInfo.DeptName FROM EmpInfo LEFT OUTER JOIN DeptInfo ON EmpInfo.DeptID = DeptInfo.DeptID"; Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource", "administrator", ""); Statement stat = con.createStatement(); ResultSet rs = stat.executeQuery(str); ©NIIT Collaborate Lesson 1C / Slide 5 of 33
  • CollaborateJDBC API • JDBC API consists of various interfaces and methods that enable the Java application to communicate with a database. • The interfaces defined in the JDBC API are categorized in two packages: • The java.sql package • The javax.sql package ©NIIT Collaborate Lesson 1C / Slide 6 of 33
  • CollaborateJDBC API (Contd.) • The java.sql Package: • Is also called the JDBC core API. • Provides the following classes and interfaces to access databases from Java applications: • Statement • PreparedStatement • CallableStatement • Connection • ResultSet • DatabaseMetaData • ResultSetMetaData ©NIIT Collaborate Lesson 1C / Slide 7 of 33
  • Collaborate JDBC API (Contd.) • The Statement Interface • The following table lists some methods of the Statement interface: Method Descriptionvoid close() Closes a Statement object and releases all the resources associated with it.void setMaxRows(int Specifies the maximum number of rows that anumRow) ResultSet object, generated by a Statement object, can store.int getMaxRows() Returns the total number of rows that can be stored in a ResultSet object.void setQueryTimeOut(int Specifies the time, in seconds, for which the driversec) should wait to allow a Statement object to execute.int getQueryTimeout() Returns the time, in seconds, for which a driver waits to allow a Statement object to execute. ©NIIT Collaborate Lesson 1C / Slide 8 of 33
  • Collaborate JDBC API (Contd.) • The PreparedStatement Interface • The following table lists some methods of the PreparedStatement interface: Method Descriptionvoid setObject(int index, Object Sets the Object, obj, as the value for theobj) parameter corresponding to the index. The index identifies the placeholder in the SQL statement for which the value needs to be set.void setDate(int index, Date Sets the java.sql.Date value for the parameterdate) corresponding to the index. The java.sql.Date class represents the SQL DATE value in JDBC.void setTime(int index, Time Sets the java.sql.Time value for the parametertime) corresponding to the index. The java.sql.Time class represents the SQL TIME value in JDBC. ©NIIT Collaborate Lesson 1C / Slide 9 of 33
  • Collaborate JDBC API (Contd.) • Methods of the PreparedStatement Interface (Contd.) Method Descriptionvoid setBlob(int index, Blob Sets the Blob type value for the parameterblob) corresponding to the index. Binary Large Object (BLOB) is a datatype that enables you to store binary objects in a database.void setClob(int index, Clob Sets the Clob type value for the parameterclob) corresponding to the index. Character Large Objects (CLOB) is a datatype that enables you to store large data in the character format in a database. ©NIIT Collaborate Lesson 1C / Slide 10 of 33
  • Collaborate JDBC API (Contd.) • The CallableStatement Interface • The following table lists some methods of the CallableStatement interface: Method Descriptionboolean getBoolean(int index) Returns the boolean value for the JDBC BIT corresponding to the index passed as a parameter.byte getByte(int index) Returns the byte value for the JDBC TINYINT corresponding to the index passed as a parameter.int getInt(int index) Returns the int value for the JDBC INTEGER corresponding to the index passed as a parameter.String getString(int index) Returns the String value for the JDBC CHAR, VARCHAR, or LONGVARCHAR corresponding to the index passed as a parameter. ©NIIT Collaborate Lesson 1C / Slide 11 of 33
  • CollaborateJDBC API (Contd.)• The Connection Interface • The following table lists some methods of the Connection interface: Method Descriptionboolean isClosed() Checks whether or not a connection with a database is closed.void setReadOnly(Boolean b) Sets the read-only mode for the connection.boolean isReadOnly() Checks whether or not a Connection object is read-only.void rollback() Rolls back the changes made to a database since the last commit or rollback operation. ©NIIT Collaborate Lesson 1C / Slide 12 of 33
  • Collaborate JDBC API (Contd.) • The ResultSet Interface • The following table lists some methods of the ResultSet interface: Method DescriptionArray getArray(int in) Returns an Array object that contains the value of the column in the current row of the ResultSet object.Statement getStatement() Returns the Statement object that has generated the ResultSet object.int getInt(String Returns the value in the column, columnName, in thecolumnName) current row of the ResultSet object as an integer type.String getString(int Returns the value of the table column in the current row ofindex) the ResultSet object as a Java String.boolean rowUpdated() Returns a boolean value that specifies whether or not the current row of the ResultSet object has been updated. ©NIIT Collaborate Lesson 1C / Slide 13 of 33
  • CollaborateJDBC API (Contd.)• The DatabaseMetaData Interface • The following table lists some methods of the DatabaseMetaData interface: Method DescriptionConnection getConnection() Returns the Connection object that has created the current metadata object.int getMaxColumnsInTable() Returns the maximum number of columns a database table can contain.int getMaxConnections() Returns the maximum number of connections that can be established with a database.int getMaxRowSize() Returns the maximum bytes that a single row in a database table can store . ©NIIT Collaborate Lesson 1C / Slide 14 of 33
  • CollaborateJDBC API (Contd.) • The methods of the DatabaseMetaData interface: (Contd.) Method Description boolean supportsGroupBy() Returns a boolean value that indicates whether or not the database supports the GROUP BY clause. The GROUP BY clause groups the result of a SELECT statement. boolean supportsUnion() Returns a boolean value that indicates whether or not the database supports the UNION operator. The UNION operator combines the results of two SELECT statements. ©NIIT Collaborate Lesson 1C / Slide 15 of 33
  • CollaborateJDBC API (Contd.)• The ResultSetMetaData Interface • The following table lists some methods of the ResultSetMetaData interface: Method Descriptionboolean isCurrency(int Returns a boolean value that indicates whethercolumn) the column stores currency value or not.boolean Returns a boolean value that indicates whetherisDefinitelyWritable(int the operations to write and update a column willcolumn) be successfully executed or not.boolean isSearchable(int Returns a boolean value that indicates whethercolumn) the column can be used in the WHERE clause of an SQL statement or not.boolean isSigned(int column) Returns a boolean value that indicates whether the value stored in the specified column is a signed number or not. ©NIIT Collaborate Lesson 1C / Slide 16 of 33
  • CollaborateJDBC API (Contd.) • The javax.sql Package: • Is also called the JDBC Standard Extension API. • Provides classes and interfaces to implement database access from Java 2 Enterprise Edition (J2EE) applications • Contains the DataSource interface. ©NIIT Collaborate Lesson 1C / Slide 17 of 33
  • Collaborate JDBC API (Contd.) • The DataSource Interface • Enables a Java application to establish a connection with a database. • The following table lists the methods of DataSource interface: Method DescriptionConnection getConnection() Establishes a database connection and returns a connection object.Connection getConnection(String Establishes a database connection afterusername, String password) verifying the username and password passed as parameters.int getLoginTimeout() Returns the maximum time, in seconds, for which a data source should wait while establishing a database connection. ©NIIT Collaborate Lesson 1C / Slide 18 of 33
  • CollaborateJDBC API (Contd.) • Methods of the DataSource interface: (Contd.) Method Description void setLoginTimeout(int Sets the maximum time, in seconds, for seconds) which a data source should wait while establishing a database connection. ©NIIT Collaborate Lesson 1C / Slide 19 of 33
  • CollaborateIsolation Levels • The transaction isolation levels in JDBC determine whether the concurrently running transactions in a database can affect each other or not. • Some common problems that might occur when multiple transactions simultaneously access a database are: • Dirty reads • Non-repeatable reads • Phantom reads ©NIIT Collaborate Lesson 1C / Slide 20 of 33
  • CollaborateIsolation Levels (Contd.) • The isolation levels enable you to isolate the concurrently running transactions so that a transaction cannot affect the result of another transaction. • The Connection interface of the JDBC API provides the following fields as int values to set isolation levels: • TRANSACTION_READ_UNCOMMITTED • TRANSACTION_READ_COMMITTED • TRANSACTION_REPEATABLE_READ • TRANSACTION_SERIALIZABLE ©NIIT Collaborate Lesson 1C / Slide 21 of 33
  • CollaborateIsolation Levels (Contd.) • The Connection interface contains the following methods to retrieve and set the value of transaction isolation level for a database: • getTransactionIsolationLevel() • setTransactionIsolationLevel() • The code snippet to use the getTransactionIsolationLevel() method is: Connection con = DriverManager.getConnection ("jdbc:odbc:MyDatasource","administrator",""); int transLevel=getTransactionIsolationLevel(); • The code snippet to use the setTransactionIsolationLevel() method is Connection con = DriverManager.getConnection ("jdbc:odbc:MyDatasource","administrator",""); int transLevel=getTransactionIsolationLevel(); con.setTransactionIsolationLevel(TRANSACTION_SERIALIZABLE); ©NIIT Collaborate Lesson 1C / Slide 22 of 33
  • CollaborateFrom the Expert’s Desk In this section, you will learn: • Best practices on: • Creating Database Access Object • Storing Connection Information in a Property File • FAQs on JDBC ©NIIT Collaborate Lesson 1C / Slide 23 of 33
  • CollaborateBest PracticesCreating a Single Database Access Object • You can create a single class to establish a connection, send SQL statements, and retrieve results from a database. • It centralizes the data access logic and any changes to the logic do not require rewriting and recompiling all application classes. • For example, you can create a Connect class in your application, all other classes of your application can use the Connect class to access the database and perform the required operation. • If any changes occur you only need to make changes in the Connect class. ©NIIT Collaborate Lesson 1C / Slide 24 of 33
  • CollaborateBest PracticesCreating a Single Database Access Object (Contd.) • The steps to create the Connect class are: • Declare the Connection object, ResultSet object, and an int variable in the Connect class as static. • Create a static method connectDb() to obtain database connection. • Create a static method processQuery() that executes SQL queries and returns a ResultSet object. • Create a static method processDML() that executes DML commands and returns an int that specifies the number of affected rows. ©NIIT Collaborate Lesson 1C / Slide 25 of 33
  • CollaborateBest PracticesStoring Connection Information in a Property File • A property file can be used to store the database connection information, such as driver name, data source name, username, and password to access a database. • You can create a file that Java developers can call in any Java application that requires database connection. • If the information specified in a property files changes, you need not change the Java application using the property file. • You need to change the information in the property file only. This prevents recompilation of the Java applications that use the property file. ©NIIT Collaborate Lesson 1C / Slide 26 of 33
  • CollaborateFAQs • Can you use the JDBC-ODBC Bridge driver with applets? Yes, you can use JDBC-ODBC bridge driver in applet to access a database. However, you need to specify permissions in the Java security policy file to allow the applet to load the Driver class. If you do not specify the permission, the Java security manager will throw an exception of type java.security.AccessControlException. This is because an applet cannot access a system resource without the proper permission. ©NIIT Collaborate Lesson 1C / Slide 27 of 33
  • CollaborateFAQs (Contd.) • To allow the applet to use the JDBC-ODBC bridge driver, creates a .java.policy file in your home directory and adds the following permission to the file: grant { permission java.lang.RuntimePermission "accessClassInPackage.sun.jdbc.odbc"; permission java.util.PropertyPermission "file.encoding", "read"; }; The above entry grants the permission, RuntimePermission, to access the sun.jdbc.odbc package that contains the JdbcOdbcDriver class and PropertyPermission to read binary files. Now you can use the Applet Viewer to test the applet. ©NIIT Collaborate Lesson 1C / Slide 28 of 33
  • CollaborateFAQs (Contd.) • Can you scroll through a ResultSet object returned from a stored procedure? You can scroll a ResultSet object that is returned from a stored procedure, if it supports JDBC 2.0 or above. ©NIIT Collaborate Lesson 1C / Slide 29 of 33
  • CollaborateFAQs (Contd.) • What are Large Objects (LOBs)? Does JDBC support LOBs? LOBs are used to retrieve and update large data, such as images, files, or scanned files in the database. JDBC 3.0 supports the use of LOB data type to store data in the database. The LOBs data are sent to the database in form of Unicode stream. There are two types of LOBs, Binary Large Objects (BLOBs) and Character Large Objects (CLOBs). JDBC 3.0 API contains methods, such as getBlob(), getClob(),setBlob(), and setClob() to retrieve and specify the data stored in LOBs. The advantages of using LOBs are: a. LOBs provide random access to data. b. LOBs allow you to search for a pattern in the data. c. LOBs enable you to determine the length of the data before actually retrieving the data. ©NIIT Collaborate Lesson 1C / Slide 30 of 33
  • CollaborateChallenge • An object of the ________ interface enables a Java application to establish a connection with a database. • The ______________ method is used to set the transaction isolation level. • The equi join retrieves data from multiple tables on the basis of the condition specified in the WHERE clause. (True/False) • Which one of the following constants sets the database isolation levels to prevent dirty reads and non-repeatable reads? • TRANSACTION_READ_UNCOMMITTED • TRANSACTION_READ_COMMITTED • TRANSACTION_REPEATABLE READ • TRANSACTION_SERIALIZABLE ©NIIT Collaborate Lesson 1C / Slide 31 of 33
  • CollaborateChallenge (Contd.) • What will be the result of executing the following code snippet? Statement sql2 = con.createStatement(); int result=sql2.executeUpdate("Select * From Publishers"); • Will throw an exception • Will result in compilation error • Will return the number of rows retrieved from Publishers table • Will return null ©NIIT Collaborate Lesson 1C / Slide 32 of 33
  • CollaborateSolutions to Challenge • Connection • setTransactionIsolationLevel() • True • a. TYPE_SCROLL_SENSITIVE • b. Will result in compilation error ©NIIT Collaborate Lesson 1C / Slide 33 of 33