SlideShare uma empresa Scribd logo
1 de 81
JDBC
JDBC Is an API spec. whose implementation comes in the form of jdbc drivers. JDBC API : java.sql.* javax.sql.*
JDBC Driver Is a bridge s/w between java application and database s/w. Is a java class that implements java.sql.Driver interface. Why we use JDBC Driver?
JDBC Architecture Application JDBC Driver Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database
JDBC Drivers Type I: “Bridge” Type II: “Native” Type III: “Middleware” Type IV: “Pure”
Type 1 Driver (jdbc - odbc bridge driver ) Oracle DB Java App that uses JDBC API Jdbc driver type1 ODBC Driver for Oracle Vendor DB Library for Oracle MS Access ODBC  Driver for MS-Access Vendor DB Library for M S Access
Type 1 Driver (Cont….) Inbuilt driver of j2sdk s/w. Suitable to interact with almost all the database s/w ’s Driver performance is very poor. Not suitable for internet programming and applet to database communication
Type 2 Driver (Native API /Partly Java Driver) Oracle DB Java App that uses JDBC API Jdbc driver type2 Vendor DB Library for Oracle MS Access Vendor DB Library for M S Access Jdbc driver type2
Type 2 Driver (cont…) Specific to each database s/w. Significantly better performance than Type 1. Odbc drivers presence is not mandatory. Not suitable for large scale applications. Not suitable for internet / applet programs Every db requires a separate driver.
Type 4 Driver (Native Protocol /All Java Driver) Oracle DB Java App that uses JDBC API Jdbc driver type4 MS Access Jdbc driver type4
Type 4 Driver (Native Protocol / All Java Driver) Completely developed in java. Can interact with db without having the support of odbc driver / vendor db library. Platform independent. Performance is good. Applet and internet programming is possible
Type 3 Driver ( Network Protocol Driver ) Java app manipulates DB data using con object Java App (Client App) DB S/W Interact using type 1,2,4 drivers Gets object from conn pool using type 3 Application Server JDBC CONNECTION POOL Release connection object back to conn pool con con con Java App (Client App) con
Type 3 Driver Is not a driver Its protocol Contains rules required to establish communication between java application and connection pool
JDBC Drivers (Fig.) JDBC Type I “Bridge” ODBC ODBC Driver Type II “Native” CLI (.lib) Middleware Server Type III “Middleware” Type IV “Pure”
Steps to develop java/jdbc App java.sql Classes ------------ Types DriverManager Date TimeStamp Interfaces  --------------- Connection Statement ResultSet Driver PreparedStatement CallableStatement
Steps to develop java/jdbc App Load the JDBC Driver class and register with DriverManager. Establish the connection with database s/w. Prepare Statement object Execute the query. Get result and process the result Close the connection.
Loading & Registering a Driver statically load driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
DriverManager All JDBC Drivers will be registered and managed by DriverManager. When a driver class is first loaded, it registers itself with the DriverManager Therefore, to register a driver, just load it!
Connection A Connection represents a session with a specific database. Establishing connection with db s/w is nothing but creating communication channel Can have multiple connections to a database Once task with connection is completed, close the connection.
Obtaining a Connection String url   = "jdbc:odbc:datasource"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); 	Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e)  	{ e.printStackTrace(); } catch (SQLException e) 	{ e.printStackTrace(); }
Statement Acts as a courier service to send queries to the db s/w. A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
Statement Methods ResultSetexecuteQuery(String)  Execute a SQL statement that returns a single ResultSet.  intexecuteUpdate(String)  Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String)  Execute a SQL statement that may return multiple results.  What is the difference between execute(-) and executeQuery(-)?
ResultSet A ResultSet object is a java object which can store bunch of selected rows given by select query execution. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data.  The 'next' method moves the cursor to the next row.
ResultSet Cursor BFR  ALR
ResultSet Methods boolean next()  activates the next row the first call to next() activates the first row returns false if there are no more rows  void close()  disposes of the ResultSet allows you to re-use the Statement that created it
ResultSet Methods TypegetType(intcolumnIndex) returns the given field as the given type fields indexed starting at 1 (not 0) TypegetType(String columnName) same, but uses name of field less efficient
ResultSet Methods String getString(int columnIndex)  boolean getBoolean(int columnIndex)  byte getByte(int columnIndex)  short getShort(int columnIndex)  int getInt(int columnIndex)  long getLong(int columnIndex)  float getFloat(int columnIndex)  double getDouble(int columnIndex)  Date getDate(int columnIndex)  Time getTime(int columnIndex)  Timestamp getTimestamp(int columnIndex)
JDBC Object Classes DriverManager Loads, chooses drivers Driver connects to actual database Connection a series of SQL statements to and from the DB Statement a single SQL statement ResultSet the records returned from a Statement
JDBC Class Usage DriverManager Driver Connection Statement ResultSet
Types of Statement Objects Statement Object PreparedStatement Object CallableStatement Object. Operations performed by Database Engine : Parse Execute Fetch 2) Parse 3) Execute 4) Fetch DB Engine Send sql query Java  App
Limitations of Statement Object DB s/w parses the same query multiple no. of times  and executes, fetches the o/p . Framing query for simple Statement object using variable is quite unnecessary. Network traffic to the DB s/w is heavy since same query goes multiple no. of times to the DB s/w. To overcome these problems use precompiled queries.
PreparedStament Object A query that goes and resides on the DB s/w without values by becoming parsed query is a precompiled query. Precompiled queries will be parsed only once, but capable of executing multiple times with same or different values. PreparedStatement object represents this precompiled query. When to use Statement object and PreparedStatement object ?
Steps to work with PreparedStatement Prepare the query having positional parameters. String query=“insert into item values(?,?,?,?)”; Positional parameter indicates value to that query will be set afterwards. Create PreparedStatement object. PreparedStatementps=con.prepareStatement(query); Set the values for positional paremeters using setType(-,-) methods. ps.setInt(-,-), ps.setString(-,-) This method makes query as a precompiled query
Steps to work with PreparedStatement Execute the query int result = ps.executeUpdate(); For more executions repeat step 3 & 4. Close PreparedStatement object ps.close()
CallableStatement DB s/w can maintain the business logic in the form of PL/SQL procedures and functions. To call PL/SQL procedures and functions from the java app , use CallableStatement. Procedure is a subprogram that performs specific action. A function is a subprogram that computes a value.  Functions and procedures are structured alike, except that functions have a RETURN clause
CallableStatement A parameter of function or procedure can be ther in three modes : in (default) out  inout Y=X*X                X=X*X in inout out
Steps to work with CallableStatement Object Create query calling procedure String query= “{ call procedure_name(?,?)}”; Create CallableStatement object CallableStatementcs=con.prepareCall(query); Register out parameters with jdbc types. Jdbc types are bridge data types between java data types and db s/w data types. cs.registerOutParameter(param_index,Types.INTEGER); Set values for IN parameters using setType(-,-). cs.setInt(parameter_index,value); Represents  procedure is available on the db s/w
Steps to work with CallableStatement Object Execute the procedure boolean b= cs.execute(); Gather the result from OUT parameter using getType() method. int result=cs.getType(column_index); For more executions repeat steps 4 , 5, and 6. Close the CallableStatement object. cs.close();
Mapping Java Types to SQL Types SQL type 	Java Type CHAR, VARCHAR, LONGVARCHAR	String NUMERIC, DECIMAL	java.math.BigDecimal BIT	boolean TINYINT	byte SMALLINT	short INTEGER	int BIGINT	long REAL	float FLOAT, DOUBLE	double BINARY, VARBINARY, LONGVARBINARY	byte[] DATE	java.sql.Date TIME	java.sql.Time TIMESTAMP	java.sql.Timestamp
Database Time Java defines three classes to help java.sql.Date year, month, day java.sql.Time hours, minutes, seconds java.sql.Timestamp year, month, day, hours, minutes, seconds, nanoseconds usually use this one
Metadata with JDBC Used to get information about tables, views, column names, column types, stored procedures, result sets, and databases. You can use database metadata to Discover database schema information. Discover database users, tables, views, and stored procedures Understand and analyze the result sets returned by SQL queries Determine the signature of a specific stored procedure in the database. Identify the primary/foreign keys for a given table
Metadata in JDBC DatabaseMetaData : Gives limitations & capabilities of underlying DB s/w. Object of a class that implements java.sql.DatabaseMetaData interface. DatabaseMetaDatadbmd=conn.getMetaData(); Invoke various methos on dbmd object to gather the details about the DB s/w pointed by Connection object. ResultsetMetaData : Gives details about table that is represented by Resultset object. Object of a class that implements java.sql.ResultsetMetaData interface. ResultsetMetaDatarsmd=resltSetOb.getMetaData();
Metadata in JDBC ParameterMetaData : Gives details about place holders kept in queries. Object of a class that implements java.sql.ParameterMetaData interface. PreparedStatementpst=con.prepareStatement( “insert into items values(?,?,?,?)”); ParameterMetaData d=pst.getParameterMetaData(); If any method invoked in DatabaseMetaData returns 0 or null , it means the driver is not capable of gathering certain information regarding DB s/w Most of the drivers doesn’t support ParameterMetaData
JDBC 2.0 Scrollable result set Batch updates Advanced data types Blobs, objects, structured types Rowsets Persistent JavaBeans JNDI Connection Pooling Distributed transactions via JTS
Scrollable ResultSet ResultSet Object Non-Scrollable ResultSet Object Scrollable ResultSet Object ResultSet object that allows to access the records in one direction is non-scrollable. ResultSet object that allows to access the records bi-directionally is called scrollable
Scrollable ResultSet JDBC 2.0 introduces scrollable results sets whose values can be read and updated if reading and updating is supported by the underlying database.  With scrollable result sets, any row can be selected at random, and the result set can be traversed forwards and backwards. One advantage to the new result set is you can update a set of matching rows without having to issue an additional executeUpdate call.
Scrollable ResultSet Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter The scroll type value can be one of the following values:  ResultSet.TYPE_FORWARD_ONLYDefault behavior in JDBC 1.0, application can only call next() on the result set.  ResultSet.SCROLL_SENSITIVEResultSet is fully navigable and updates are reflected in the result set as they occur.  ResultSet.SCROLL_INSENSITIVEResult set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results.
Scrollable ResultSet The update type parameter can be one of the following two values:  ResultSet.CONCUR_READ_ONLYThe result set is read only.  ResultSet.CONCUR_UPDATABLEThe result set can be updated.  You can verify that your database supports these types by calling : con.getMetaData().supportsResultSetConcurrency() method
Navigating the ResultSet The fully scrollable result set returns a cursor which can be moved using simple commands. By default the result set cursor points to the row before the first row of the result set.  A call to next() retrieves the first result set row beforeFirst(): Default position. Puts cursor before the first row of the result set.  first(): Puts cursor on the first row of the result set.  last(): Puts cursor before the last row of the result set.  afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet.  absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.  relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.
Updatable ResultSet Object If modifications done in the ResultSet object is reflecting in the DB table, then ResultSet object is called as Updatable ResultSet object. We can perform insert, update, delete operations on the table without SQL statements. You can update a value in a result set by calling the ResultSet.update<type> method on the row where the cursor is positioned The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database Closing the result set before calling updateRow will lose any edits applied to the result set
Updatable ResultSet Object Inserting a new row uses the same update<type> methods rs.moveToInsertRow is called before and rs.insertRow() is called after the fields have been initialized You can delete the current row with a call to rs.deleteRow() Is not suitable for bulk delete and bulk update operations. Only ScrollableResultSet can become UpdatableResultSet.
Batch Processing Is a process of combining related queries into single unit, sending them to DB s/w as batch and getting their result as a batch. Instead of sending multiple queries to DB s/w for multiple times, send queries as a batch. Reduces network round trips between java application and DB s/w. Helps the programmer to work with Transactions.
Batch Processing The calls to stmt.addBatch(-) append statements to the original Statement. The call to executeBatch() submits the entire statement with all the appends to the database. The return result of the addBatch method is an array of row counts affected for each statement executed in the batch job. If a problem occurred, a java.sql.BatchUpdateException is thrown. Once select query is executed , it generates ResultSet object. Since ResultSet object cannot be stored in integer array, batch processing cannot include select queries.
Transaction Management Is all about combining set of related operations into a single unit and executing them by applying do everything or nothing principle Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed default case: true
setAutoCommit Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()
RowSets We can send only those java objects over the network which are serializable. ResultSet object is not a serializable object, so we cannot send that object over network. To overcome this problem jdbc has given support for RowSet  object which are extension to ResultSet object and can be sent over network. All JDBC drivers doesn’t support RowSets.
Performance Tuning For JDBC API
Why Optimize? On average, a web request performs 4 database queries. Experience has shown that database calls are typical performance bottleneck. Bad JDBC can overwhelm the database.
JDBC API SQL: “SELECT * FROM TABLE” java.sql.PreparedStatement java.sql.CallableStatement Cache data on client. MOST VERSATILE MOST OPTIMIZATION
JDBC API SQL STATEMENTS Most flexible Least reliable Must be recompiled in database for each use PREPARED STATEMENT Represents a precompiled SQL statement Can be used to efficiently execute statement multiple times Somewhat flexible –can create new ones as needed
JDBC API CALLABLE STATEMENT Used to execute SQL stored procedures.  Same syntax as PreparedStatement. Least flexible. Most optimized DB call. PreparedStatement gives better performance when compared to Statement because it is pre-parsed and pre-compiled by the database once for the first time and then onwards it reuses the parsed and compiled statement. CallableStatement gives better performance when compared to PreparedStatement and Statement when there is a requirement for single request to process multiple complex statements
JDBC API CACHE Keep data within client to reduce the number of round-trips to the database. Every database schema generally has read-only and read-mostly tables. These tables are called as lookup tables. Read-only tables contain static data that never changes in its life time. Read-mostly tables contain semi dynamic data that changes often If an application reads data from these tables for every client request, then it is redundant, unnecessary and expensive.  The solution for this problem is to cache the read-only table data by reading the data from that table once and caching the read-mostly table data by reading and refreshing with time limit
Basic Design Techniques Use Database Connection Pool Don’t useDriverManager.getConnection() often. JDBC connections can take 0.5 to 2 seconds to create. Create Pool of Connections and reuse them. Use multi-threading with Connection Pooling to address network latency Threads can issue queries over separate database connections. OPTIMIZATION WITH RESULTSET OBJECT Set up proper direction for processing the rows Use proper get methods Close ResultSet when finished
Basic Design Techniques Single-batch Transactions Collect set of operations and submit transaction in one statement BEGIN TRANSACTION     	UPDATE TABLE1...  	INSERT INTO TABLE2… 		DELETE TABLE3 	COMMIT DB obtains necessary locks on rows and tables, uses and releases them in one step
Basic Design Techniques Smart Queries Make queries as specific as possible Put more logic into SQL statements DB are designed to use SQL efficiently Proper use of SQL can avoid performance problems Smart Query Ex: get employees in ENG dept Instead of:  		SELECT * FROM employees; 	     	SELECT * FROM dept; 		(and joining on Java application side) Use database join: 	SELECT employees.* FROM employees E, dept D WHERE E.DEPTNO = D.DEPTNO AND D.DEPTTYPE = ‘ENG’;
Basic Design Techniques Smart Query Guidelines Use DB for filtering Use Java for business logic DB does filtering very well DB business logic is poor
Connection Pooling There are two types of jdbc connection objects : Direct Connection Object Pooled Connection Object The JDBC Connection object that is created by the programmer manually is called direct connection object. The JDBC Connection object that is collected from JDBC Connection pool is called pooled connection object. JDBC Connection pool is a factory that contains set of readily available JDBC connection objects.
Connection Pooling Using connection pools helps to both alleviate connection management overhead and decrease development tasks for data access. Each time an application attempts to access a backend store (such as a database), it requires resources to create, maintain, and release a connection to that datastore. To mitigate the strain this process can place on overall application resources, the Application Server enables administrators to establish a pool of backend connections that applications can share on an application server
Advantages of Connection Pooling Connection pooling can improve the response time of any application that requires connections, especially Web-based applications. With connection pooling, most user requests do not incur the overhead of creating a new connection because the data source can locate and use an existing connection from the pool of connections Re usability, we can reuse the existing connection already existing It also simplifies the design in terms of managing the connections; we can delegate the connection creation, max number of connections for an application, max idle time for a connection etc. using the some kind of a connection pool manager
C3P0 Connection Pooling c3p0 is an easy-to-use library for making traditional JDBC drivers "enterprise-ready" by augmenting them with functionality defined by the jdbc3 spec and the optional extensions to jdbc2 c3p0 provides several useful services: Classes which adapt traditional DriverManager-based JDBC drivers to the new javax.sql.DataSource scheme for acquiring database Connections. Transparent pooling of Connection and PreparedStatements behind DataSources which can "wrap" around traditional drivers or arbitrary unpooledDataSources.
Working with C3P0 Connection Pool Put the file lib/c3p0-0.9.1.2.jar somewhere in your CLASSPATH There are three ways of acquiring c3p0 pool-backed DataSources: directly instantiate and configure a ComboPooledDataSource bean use the DataSources factory class "build your own" pool-backed DataSource by directly instantiating PoolBackedDataSource and setting its ConectionPoolDataSource
Instantiating and Configuring a ComboPooledDataSource the most straightforward way to create a c3p0 pooling DataSource is to instantiate an instance of com.mchange.v2.c3p0.ComboPooledDataSource This is a JavaBean-style class with a public, no-arg constructor Before you use the DataSource, you'll have to be sure to set at least the property jdbcUrl You may also want to set user and password, and if you have not externally preloaded the old-style JDBC driver you'll use you should set the driverClass.
Using the DataSources factory class use the static factory class com.mchange.v2.c3p0.DataSources Can be used to build unpooledDataSources from traditional JDBC drivers Can be used to build pooled DataSources from unpooledDataSources If you use the DataSources factory class, and you want to programmatically override default configuration parameters, you can supply a map of override properties
Java Naming And Directory Interface (JNDI) Java application uses JNDI API to interact with Naming Registry s/w. Every JDBC Connection pool will be represented by Data Source object. To make this data source object publically visible, we register data source object in a special place called naming registry having nick name (jndi name). In order to access a JDBC Connection object of a Connection pool, we need to access the data source object pointing to that connection pool.
Java Naming And Directory Interface (JNDI) Java application needs to perform look up or search operation on naming registry to get the data source object. Use getConnection () method on the data source object to get the connection object from the connection pool.
An open source DataBase Management System  Community Editions free Enterprise Editions free license but a subscription and maintenance fee Suitable situations range from small enterprise to global, enterprise-wide systems  Multiple platforms
MySQL Tools The core system includes only a command-line tool ‘mysqladmin’ GUI tools available separately from MySQL are  ‘MySQL Administrator’ (a DBA tool) and  ‘MySQL Query Browser’
SQLyog is a GUI front-end for MySQL (there are others) - Community and Enterprise Editions Allows Data Definition and Data Manipulation After loading it and before using it you need to ‘Connect’ to the right MySQL instance A tutorial, with a range of activities to get familiar with it, is available at http://www.databasejournal.com/features/mysql/article.php/1558731
SQLyog screen
References For further information see www.mysql.com www.webyog.com/en/ includes forums and FAQs

Mais conteúdo relacionado

Mais procurados

Java Presentation
Java PresentationJava Presentation
Java Presentation
pm2214
 

Mais procurados (20)

Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java threads
Java threadsJava threads
Java threads
 
Files in java
Files in javaFiles in java
Files in java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
php
phpphp
php
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
JDBC
JDBCJDBC
JDBC
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java Applet
Java AppletJava Applet
Java Applet
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Java program structure
Java program structureJava program structure
Java program structure
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 

Destaque

Java session16
Java session16Java session16
Java session16
Niit Care
 
Interface result set
Interface result setInterface result set
Interface result set
myrajendra
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
myrajendra
 

Destaque (20)

Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Database Connectivity with JDBC
Database Connectivity with JDBCDatabase Connectivity with JDBC
Database Connectivity with JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Java session16
Java session16Java session16
Java session16
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 
Interface result set
Interface result setInterface result set
Interface result set
 
Properties
PropertiesProperties
Properties
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 
Interface callable statement
Interface callable statementInterface callable statement
Interface callable statement
 
Jdbc
JdbcJdbc
Jdbc
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 

Semelhante a Database Access With JDBC

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
leminhvuong
 

Semelhante a Database Access With JDBC (20)

Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc
JdbcJdbc
Jdbc
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Lecture17
Lecture17Lecture17
Lecture17
 
JDBC
JDBCJDBC
JDBC
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 
JDBC
JDBCJDBC
JDBC
 
11. jdbc
11. jdbc11. jdbc
11. jdbc
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Jdbc
JdbcJdbc
Jdbc
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Database Access With JDBC

  • 2. JDBC Is an API spec. whose implementation comes in the form of jdbc drivers. JDBC API : java.sql.* javax.sql.*
  • 3. JDBC Driver Is a bridge s/w between java application and database s/w. Is a java class that implements java.sql.Driver interface. Why we use JDBC Driver?
  • 4. JDBC Architecture Application JDBC Driver Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database
  • 5. JDBC Drivers Type I: “Bridge” Type II: “Native” Type III: “Middleware” Type IV: “Pure”
  • 6. Type 1 Driver (jdbc - odbc bridge driver ) Oracle DB Java App that uses JDBC API Jdbc driver type1 ODBC Driver for Oracle Vendor DB Library for Oracle MS Access ODBC Driver for MS-Access Vendor DB Library for M S Access
  • 7. Type 1 Driver (Cont….) Inbuilt driver of j2sdk s/w. Suitable to interact with almost all the database s/w ’s Driver performance is very poor. Not suitable for internet programming and applet to database communication
  • 8. Type 2 Driver (Native API /Partly Java Driver) Oracle DB Java App that uses JDBC API Jdbc driver type2 Vendor DB Library for Oracle MS Access Vendor DB Library for M S Access Jdbc driver type2
  • 9. Type 2 Driver (cont…) Specific to each database s/w. Significantly better performance than Type 1. Odbc drivers presence is not mandatory. Not suitable for large scale applications. Not suitable for internet / applet programs Every db requires a separate driver.
  • 10. Type 4 Driver (Native Protocol /All Java Driver) Oracle DB Java App that uses JDBC API Jdbc driver type4 MS Access Jdbc driver type4
  • 11. Type 4 Driver (Native Protocol / All Java Driver) Completely developed in java. Can interact with db without having the support of odbc driver / vendor db library. Platform independent. Performance is good. Applet and internet programming is possible
  • 12. Type 3 Driver ( Network Protocol Driver ) Java app manipulates DB data using con object Java App (Client App) DB S/W Interact using type 1,2,4 drivers Gets object from conn pool using type 3 Application Server JDBC CONNECTION POOL Release connection object back to conn pool con con con Java App (Client App) con
  • 13. Type 3 Driver Is not a driver Its protocol Contains rules required to establish communication between java application and connection pool
  • 14. JDBC Drivers (Fig.) JDBC Type I “Bridge” ODBC ODBC Driver Type II “Native” CLI (.lib) Middleware Server Type III “Middleware” Type IV “Pure”
  • 15. Steps to develop java/jdbc App java.sql Classes ------------ Types DriverManager Date TimeStamp Interfaces --------------- Connection Statement ResultSet Driver PreparedStatement CallableStatement
  • 16. Steps to develop java/jdbc App Load the JDBC Driver class and register with DriverManager. Establish the connection with database s/w. Prepare Statement object Execute the query. Get result and process the result Close the connection.
  • 17. Loading & Registering a Driver statically load driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
  • 18. DriverManager All JDBC Drivers will be registered and managed by DriverManager. When a driver class is first loaded, it registers itself with the DriverManager Therefore, to register a driver, just load it!
  • 19. Connection A Connection represents a session with a specific database. Establishing connection with db s/w is nothing but creating communication channel Can have multiple connections to a database Once task with connection is completed, close the connection.
  • 20. Obtaining a Connection String url = "jdbc:odbc:datasource"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
  • 21. Statement Acts as a courier service to send queries to the db s/w. A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
  • 22. Statement Methods ResultSetexecuteQuery(String) Execute a SQL statement that returns a single ResultSet. intexecuteUpdate(String) Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) Execute a SQL statement that may return multiple results. What is the difference between execute(-) and executeQuery(-)?
  • 23. ResultSet A ResultSet object is a java object which can store bunch of selected rows given by select query execution. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row.
  • 25. ResultSet Methods boolean next() activates the next row the first call to next() activates the first row returns false if there are no more rows void close() disposes of the ResultSet allows you to re-use the Statement that created it
  • 26. ResultSet Methods TypegetType(intcolumnIndex) returns the given field as the given type fields indexed starting at 1 (not 0) TypegetType(String columnName) same, but uses name of field less efficient
  • 27. ResultSet Methods String getString(int columnIndex) boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex) Timestamp getTimestamp(int columnIndex)
  • 28. JDBC Object Classes DriverManager Loads, chooses drivers Driver connects to actual database Connection a series of SQL statements to and from the DB Statement a single SQL statement ResultSet the records returned from a Statement
  • 29. JDBC Class Usage DriverManager Driver Connection Statement ResultSet
  • 30. Types of Statement Objects Statement Object PreparedStatement Object CallableStatement Object. Operations performed by Database Engine : Parse Execute Fetch 2) Parse 3) Execute 4) Fetch DB Engine Send sql query Java App
  • 31. Limitations of Statement Object DB s/w parses the same query multiple no. of times and executes, fetches the o/p . Framing query for simple Statement object using variable is quite unnecessary. Network traffic to the DB s/w is heavy since same query goes multiple no. of times to the DB s/w. To overcome these problems use precompiled queries.
  • 32. PreparedStament Object A query that goes and resides on the DB s/w without values by becoming parsed query is a precompiled query. Precompiled queries will be parsed only once, but capable of executing multiple times with same or different values. PreparedStatement object represents this precompiled query. When to use Statement object and PreparedStatement object ?
  • 33. Steps to work with PreparedStatement Prepare the query having positional parameters. String query=“insert into item values(?,?,?,?)”; Positional parameter indicates value to that query will be set afterwards. Create PreparedStatement object. PreparedStatementps=con.prepareStatement(query); Set the values for positional paremeters using setType(-,-) methods. ps.setInt(-,-), ps.setString(-,-) This method makes query as a precompiled query
  • 34. Steps to work with PreparedStatement Execute the query int result = ps.executeUpdate(); For more executions repeat step 3 & 4. Close PreparedStatement object ps.close()
  • 35. CallableStatement DB s/w can maintain the business logic in the form of PL/SQL procedures and functions. To call PL/SQL procedures and functions from the java app , use CallableStatement. Procedure is a subprogram that performs specific action. A function is a subprogram that computes a value. Functions and procedures are structured alike, except that functions have a RETURN clause
  • 36. CallableStatement A parameter of function or procedure can be ther in three modes : in (default) out inout Y=X*X X=X*X in inout out
  • 37. Steps to work with CallableStatement Object Create query calling procedure String query= “{ call procedure_name(?,?)}”; Create CallableStatement object CallableStatementcs=con.prepareCall(query); Register out parameters with jdbc types. Jdbc types are bridge data types between java data types and db s/w data types. cs.registerOutParameter(param_index,Types.INTEGER); Set values for IN parameters using setType(-,-). cs.setInt(parameter_index,value); Represents procedure is available on the db s/w
  • 38. Steps to work with CallableStatement Object Execute the procedure boolean b= cs.execute(); Gather the result from OUT parameter using getType() method. int result=cs.getType(column_index); For more executions repeat steps 4 , 5, and 6. Close the CallableStatement object. cs.close();
  • 39. Mapping Java Types to SQL Types SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp
  • 40. Database Time Java defines three classes to help java.sql.Date year, month, day java.sql.Time hours, minutes, seconds java.sql.Timestamp year, month, day, hours, minutes, seconds, nanoseconds usually use this one
  • 41. Metadata with JDBC Used to get information about tables, views, column names, column types, stored procedures, result sets, and databases. You can use database metadata to Discover database schema information. Discover database users, tables, views, and stored procedures Understand and analyze the result sets returned by SQL queries Determine the signature of a specific stored procedure in the database. Identify the primary/foreign keys for a given table
  • 42. Metadata in JDBC DatabaseMetaData : Gives limitations & capabilities of underlying DB s/w. Object of a class that implements java.sql.DatabaseMetaData interface. DatabaseMetaDatadbmd=conn.getMetaData(); Invoke various methos on dbmd object to gather the details about the DB s/w pointed by Connection object. ResultsetMetaData : Gives details about table that is represented by Resultset object. Object of a class that implements java.sql.ResultsetMetaData interface. ResultsetMetaDatarsmd=resltSetOb.getMetaData();
  • 43. Metadata in JDBC ParameterMetaData : Gives details about place holders kept in queries. Object of a class that implements java.sql.ParameterMetaData interface. PreparedStatementpst=con.prepareStatement( “insert into items values(?,?,?,?)”); ParameterMetaData d=pst.getParameterMetaData(); If any method invoked in DatabaseMetaData returns 0 or null , it means the driver is not capable of gathering certain information regarding DB s/w Most of the drivers doesn’t support ParameterMetaData
  • 44. JDBC 2.0 Scrollable result set Batch updates Advanced data types Blobs, objects, structured types Rowsets Persistent JavaBeans JNDI Connection Pooling Distributed transactions via JTS
  • 45. Scrollable ResultSet ResultSet Object Non-Scrollable ResultSet Object Scrollable ResultSet Object ResultSet object that allows to access the records in one direction is non-scrollable. ResultSet object that allows to access the records bi-directionally is called scrollable
  • 46. Scrollable ResultSet JDBC 2.0 introduces scrollable results sets whose values can be read and updated if reading and updating is supported by the underlying database. With scrollable result sets, any row can be selected at random, and the result set can be traversed forwards and backwards. One advantage to the new result set is you can update a set of matching rows without having to issue an additional executeUpdate call.
  • 47. Scrollable ResultSet Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter The scroll type value can be one of the following values: ResultSet.TYPE_FORWARD_ONLYDefault behavior in JDBC 1.0, application can only call next() on the result set. ResultSet.SCROLL_SENSITIVEResultSet is fully navigable and updates are reflected in the result set as they occur. ResultSet.SCROLL_INSENSITIVEResult set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results.
  • 48. Scrollable ResultSet The update type parameter can be one of the following two values: ResultSet.CONCUR_READ_ONLYThe result set is read only. ResultSet.CONCUR_UPDATABLEThe result set can be updated. You can verify that your database supports these types by calling : con.getMetaData().supportsResultSetConcurrency() method
  • 49. Navigating the ResultSet The fully scrollable result set returns a cursor which can be moved using simple commands. By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row beforeFirst(): Default position. Puts cursor before the first row of the result set. first(): Puts cursor on the first row of the result set. last(): Puts cursor before the last row of the result set. afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet. absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row. relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.
  • 50. Updatable ResultSet Object If modifications done in the ResultSet object is reflecting in the DB table, then ResultSet object is called as Updatable ResultSet object. We can perform insert, update, delete operations on the table without SQL statements. You can update a value in a result set by calling the ResultSet.update<type> method on the row where the cursor is positioned The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database Closing the result set before calling updateRow will lose any edits applied to the result set
  • 51. Updatable ResultSet Object Inserting a new row uses the same update<type> methods rs.moveToInsertRow is called before and rs.insertRow() is called after the fields have been initialized You can delete the current row with a call to rs.deleteRow() Is not suitable for bulk delete and bulk update operations. Only ScrollableResultSet can become UpdatableResultSet.
  • 52. Batch Processing Is a process of combining related queries into single unit, sending them to DB s/w as batch and getting their result as a batch. Instead of sending multiple queries to DB s/w for multiple times, send queries as a batch. Reduces network round trips between java application and DB s/w. Helps the programmer to work with Transactions.
  • 53. Batch Processing The calls to stmt.addBatch(-) append statements to the original Statement. The call to executeBatch() submits the entire statement with all the appends to the database. The return result of the addBatch method is an array of row counts affected for each statement executed in the batch job. If a problem occurred, a java.sql.BatchUpdateException is thrown. Once select query is executed , it generates ResultSet object. Since ResultSet object cannot be stored in integer array, batch processing cannot include select queries.
  • 54. Transaction Management Is all about combining set of related operations into a single unit and executing them by applying do everything or nothing principle Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed default case: true
  • 55. setAutoCommit Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()
  • 56. RowSets We can send only those java objects over the network which are serializable. ResultSet object is not a serializable object, so we cannot send that object over network. To overcome this problem jdbc has given support for RowSet object which are extension to ResultSet object and can be sent over network. All JDBC drivers doesn’t support RowSets.
  • 58. Why Optimize? On average, a web request performs 4 database queries. Experience has shown that database calls are typical performance bottleneck. Bad JDBC can overwhelm the database.
  • 59. JDBC API SQL: “SELECT * FROM TABLE” java.sql.PreparedStatement java.sql.CallableStatement Cache data on client. MOST VERSATILE MOST OPTIMIZATION
  • 60. JDBC API SQL STATEMENTS Most flexible Least reliable Must be recompiled in database for each use PREPARED STATEMENT Represents a precompiled SQL statement Can be used to efficiently execute statement multiple times Somewhat flexible –can create new ones as needed
  • 61. JDBC API CALLABLE STATEMENT Used to execute SQL stored procedures. Same syntax as PreparedStatement. Least flexible. Most optimized DB call. PreparedStatement gives better performance when compared to Statement because it is pre-parsed and pre-compiled by the database once for the first time and then onwards it reuses the parsed and compiled statement. CallableStatement gives better performance when compared to PreparedStatement and Statement when there is a requirement for single request to process multiple complex statements
  • 62. JDBC API CACHE Keep data within client to reduce the number of round-trips to the database. Every database schema generally has read-only and read-mostly tables. These tables are called as lookup tables. Read-only tables contain static data that never changes in its life time. Read-mostly tables contain semi dynamic data that changes often If an application reads data from these tables for every client request, then it is redundant, unnecessary and expensive. The solution for this problem is to cache the read-only table data by reading the data from that table once and caching the read-mostly table data by reading and refreshing with time limit
  • 63. Basic Design Techniques Use Database Connection Pool Don’t useDriverManager.getConnection() often. JDBC connections can take 0.5 to 2 seconds to create. Create Pool of Connections and reuse them. Use multi-threading with Connection Pooling to address network latency Threads can issue queries over separate database connections. OPTIMIZATION WITH RESULTSET OBJECT Set up proper direction for processing the rows Use proper get methods Close ResultSet when finished
  • 64. Basic Design Techniques Single-batch Transactions Collect set of operations and submit transaction in one statement BEGIN TRANSACTION UPDATE TABLE1... INSERT INTO TABLE2… DELETE TABLE3 COMMIT DB obtains necessary locks on rows and tables, uses and releases them in one step
  • 65. Basic Design Techniques Smart Queries Make queries as specific as possible Put more logic into SQL statements DB are designed to use SQL efficiently Proper use of SQL can avoid performance problems Smart Query Ex: get employees in ENG dept Instead of: SELECT * FROM employees; SELECT * FROM dept; (and joining on Java application side) Use database join: SELECT employees.* FROM employees E, dept D WHERE E.DEPTNO = D.DEPTNO AND D.DEPTTYPE = ‘ENG’;
  • 66. Basic Design Techniques Smart Query Guidelines Use DB for filtering Use Java for business logic DB does filtering very well DB business logic is poor
  • 67. Connection Pooling There are two types of jdbc connection objects : Direct Connection Object Pooled Connection Object The JDBC Connection object that is created by the programmer manually is called direct connection object. The JDBC Connection object that is collected from JDBC Connection pool is called pooled connection object. JDBC Connection pool is a factory that contains set of readily available JDBC connection objects.
  • 68. Connection Pooling Using connection pools helps to both alleviate connection management overhead and decrease development tasks for data access. Each time an application attempts to access a backend store (such as a database), it requires resources to create, maintain, and release a connection to that datastore. To mitigate the strain this process can place on overall application resources, the Application Server enables administrators to establish a pool of backend connections that applications can share on an application server
  • 69. Advantages of Connection Pooling Connection pooling can improve the response time of any application that requires connections, especially Web-based applications. With connection pooling, most user requests do not incur the overhead of creating a new connection because the data source can locate and use an existing connection from the pool of connections Re usability, we can reuse the existing connection already existing It also simplifies the design in terms of managing the connections; we can delegate the connection creation, max number of connections for an application, max idle time for a connection etc. using the some kind of a connection pool manager
  • 70. C3P0 Connection Pooling c3p0 is an easy-to-use library for making traditional JDBC drivers "enterprise-ready" by augmenting them with functionality defined by the jdbc3 spec and the optional extensions to jdbc2 c3p0 provides several useful services: Classes which adapt traditional DriverManager-based JDBC drivers to the new javax.sql.DataSource scheme for acquiring database Connections. Transparent pooling of Connection and PreparedStatements behind DataSources which can "wrap" around traditional drivers or arbitrary unpooledDataSources.
  • 71. Working with C3P0 Connection Pool Put the file lib/c3p0-0.9.1.2.jar somewhere in your CLASSPATH There are three ways of acquiring c3p0 pool-backed DataSources: directly instantiate and configure a ComboPooledDataSource bean use the DataSources factory class "build your own" pool-backed DataSource by directly instantiating PoolBackedDataSource and setting its ConectionPoolDataSource
  • 72. Instantiating and Configuring a ComboPooledDataSource the most straightforward way to create a c3p0 pooling DataSource is to instantiate an instance of com.mchange.v2.c3p0.ComboPooledDataSource This is a JavaBean-style class with a public, no-arg constructor Before you use the DataSource, you'll have to be sure to set at least the property jdbcUrl You may also want to set user and password, and if you have not externally preloaded the old-style JDBC driver you'll use you should set the driverClass.
  • 73. Using the DataSources factory class use the static factory class com.mchange.v2.c3p0.DataSources Can be used to build unpooledDataSources from traditional JDBC drivers Can be used to build pooled DataSources from unpooledDataSources If you use the DataSources factory class, and you want to programmatically override default configuration parameters, you can supply a map of override properties
  • 74. Java Naming And Directory Interface (JNDI) Java application uses JNDI API to interact with Naming Registry s/w. Every JDBC Connection pool will be represented by Data Source object. To make this data source object publically visible, we register data source object in a special place called naming registry having nick name (jndi name). In order to access a JDBC Connection object of a Connection pool, we need to access the data source object pointing to that connection pool.
  • 75. Java Naming And Directory Interface (JNDI) Java application needs to perform look up or search operation on naming registry to get the data source object. Use getConnection () method on the data source object to get the connection object from the connection pool.
  • 76.
  • 77. An open source DataBase Management System Community Editions free Enterprise Editions free license but a subscription and maintenance fee Suitable situations range from small enterprise to global, enterprise-wide systems Multiple platforms
  • 78. MySQL Tools The core system includes only a command-line tool ‘mysqladmin’ GUI tools available separately from MySQL are ‘MySQL Administrator’ (a DBA tool) and ‘MySQL Query Browser’
  • 79. SQLyog is a GUI front-end for MySQL (there are others) - Community and Enterprise Editions Allows Data Definition and Data Manipulation After loading it and before using it you need to ‘Connect’ to the right MySQL instance A tutorial, with a range of activities to get familiar with it, is available at http://www.databasejournal.com/features/mysql/article.php/1558731
  • 81. References For further information see www.mysql.com www.webyog.com/en/ includes forums and FAQs