* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Module 12: Connecting to a Database
		                    
		                    
								Survey							
                            
		                
		                
                            
                            
								Document related concepts							
                        
                        
                    
						
						
							Transcript						
					
					Connecting to a Database
225 City Avenue, Suite 106
Bala Cynwyd, PA 19004
610.206.0101, phone
610.206.0102, fax
www.learnquest.com
Learning Objectives
 Drivers
 The DriverManager Class
 Connection Failure
 Read-Only Connections
 Using JDBC Drivers
 Closing the Connection
 Database Connections
 Summary
 Connecting to a Database
2
Drivers
 The java.sql package defines interfaces that
describe how Java will connect to a database
 Vendors provide implementations of these interfaces
which allow a Java program to connect to a particular
RDBMS (Oracle, DB2 etc.)
 This vendor provided code is called a “Driver”
3
The DriverManager Class
 If your program needs to connect to two different
RDBMSs (DB2, Oracle) it will need to have two sets of
drivers loaded at the same time. The DriverManager
class manages these drivers
 DriverManager keeps track of the drivers that are
available and handles establishing a connection
between a database and the appropriate driver
 It manages events such as driver login time limits and
the printing of log and tracing messages
4
Using JDBC Drivers
 A Driver class is loaded and registered with the
DriverManager in one of two ways:
 By calling the method Class.forName
 By adding the Driver class to the java.lang.System
property jdbc.drivers
7
The JDBC-ODBC Driver
 Java contains a built-in driver called the JDBC-ODBC
driver. It uses Open Database Connectivity to allow a
program to connect to any database that is ODBC
compliant. Such databases include Microsoft Access,
SQL-Server, Cloudscape and others
 The JDBC-ODBC driver does not perform well
enough to be used for anything other than testing
8
Example: Loading a Driver
try {
// loading the JDBC-ODBC Driver
Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Message: “ +
e.getMessage());
}
9
Using JDBC Drivers
Types of JDBC Drivers:
Type 1
Type 2
Type 3
Type 4
JDBC-ODBC bridge
Native-API
JDBC-Net
Native-protocol
third party API
partly-Java driver
pure Java driver
pure Java driver
In general the higher numbered drivers are preferred. In
practice you will simply use a driver provided by the
vendor
10
Database Connections
 Once the driver is loaded you must establish a
connection to the database using the
getConnection() method of the DriverManager
class
 getConnection() accepts a vendor specific string
which holds the database location and other
connection information
 A user can get information about a Connection
object's database by invoking the
Connection.getMetaData method
12
Data Sources
 The JDBC 2.0 Standard Extension API provides the
DataSource interface as an alternative to the
DriverManager for establishing a connection
 Data sources create pools of connections that can be
reused by different programs. If many different
programs need to connect to the same database a
datasource can provide better performance than
simply setting up a separate connection in each and
every program
 Data sources are used in J2EE
13
Connecting to a Database (con’t)
 When an application uses the DriverManager to
create a Connection object it must supply a URL to
the DriverManager.getConnection method
 A JDBC URL provides a way of identifying a data
source so that the appropriate driver will recognize it
and establish a connection with it
 The standard syntax for JDBC URLs:
jdbc:<subprotocol>:<subname>
15
The JDBC URL
 A URL (Uniform Resource Locator) gives information for
locating a resource on the Internet. It can be thought of
as an address
 The JDBC URL is composed of:
 Jdbc – the protocol. The protocol in a JDBC URL is always jdbc
 <subprotocol> - the name of the driver or the name of a database
connectivity mechanism, which may be supported by one or more
drivers
 <subname> - a way to identify the data source
• The subname can vary depending on the subprotocol and it can have any
internal syntax the driver writer chooses including a subname
• The point of a subname is to give enough information to locate the data
source
16
Connection Example
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Define the DSN(Data Source Name)
String url = "Jdbc:Odbc:JdbcLab";
String databaseUser = "";
String databasePassword = "";
Connection databaseConnection =
DriverManager.getConnection(url,databaseUser,
databasePassword);
}
catch(Exception e) {
// error processing here… }
17
Common Connection Problems
 If the Connection fails with the message “Class not
found” it usually means that the Driver is not in the
CLASSPATH
 If the Connection fails with the message “Driver not
found” it usually means that the Driver has not been
registered with the DriverManager
18
Read-Only Connections
 One can put the connection to the database in
read-only mode as a hint to the driver to enable
database optimizations
 The method of Connection interface
setReadOnly() is used to establish read-only
connection
 The method of Connection interface isReadOnly()
is used to get an information whether Connection
object is in read-only mode
19
Closing the Connection
 It is recommended that one explicitly closes database
connections when they are no longer needed:
myConnection.close();
 A Connection object is automatically closed when it is
garbage collected
 Also certain fatal errors can close a Connection
object
20
Summary
 The DriverManager class provides a method to
establish a connection with a database
 The traditional way to establish a connection with a
database is to use DriverManager.getConnection
method
 It is recommended that programmers explicitly close all
connections with the method Connection.close() as
soon as they are no longer needed, thereby freeing
DBMS resources as early as possible
21
Any Questions?
After discussing this chapter
with your instructor please
complete the exercises in Lab 9
22