Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 4

JDBC

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

Connection connection = null;

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().)

// Load the JDBC driver


String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName);
// Create a connection to the database
String serverName = "127.0.0.1";
String portNumber = "1521";
String sid = "mydatabase";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "username"; String password = "password";
connection = DriverManager.getConnection(url, username, password);
System.out.println("Connectedtothedatabase");

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();
}

You might also like