Professional Documents
Culture Documents
What Is Connectivity? - Establish A Connection. - A JDBC™ Application Connects To A Target Data Source Using One of Two Mechanisms
What Is Connectivity? - Establish A Connection. - A JDBC™ Application Connects To A Target Data Source Using One of Two Mechanisms
What is Connectivity?
Establish a connection.
A JDBC application connects to a target data source using one of two mechanisms
DriverManager:
The fully implemented class requires an application to load a
specific driver, using a hardcoded URL.
This initialization, the DriverManager class attempts to load the
driver classes referenced in the jdbc.drivers system property.
Customization of the drivers to fit your programming
requirements.
DataSource:
Preferred over DriverManager because it allows details about
the underlying data source to be transparent to your
application
. A DataSource object's properties are set so that it represents
a particular data source.
Statements
Statement the statement is sent to
the database server each and every
time.
PreparedStatement the statement
is cached and then the execution
path is pre determined on the
database server allowing it to be
executed multiple times in an
efficient manner.
CallableStatement used for
Connection String
The method Class.forName(String) is used to load the JDBC driver class. The line
below causes the JDBC driver from some jdbc vendor to be loaded into the
application. (Some JVMs also require the class to be instantiated with
.newInstance().)
Create Statement
Data is retrieved from the database using a database query mechanism. The example below shows
creating a statement and executing a query.
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );
try {
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
// Column numbers start at 1.
// Also there are many methods on the result set to return
// the column as a particular type.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}