Sie sind auf Seite 1von 31

Java Database

Connectivity (JDBC)
Java Database Connectivity
Java Database Connectivity (JDBC)
Is an API that helps you to query a database, or
any other data source for which a JDBC driver is
available.
Using JDBC, you can directly from your Java
programs
establish a connection to a relational database
query a database for information
modify the contents of a database
The classes and interfaces in the java.sql
package
JDBC Drivers
JDBC driver
A small piece of software that instructs JDBC how to connect to
and interact with a particular type of database.
The JDBC drivers facilitate JDBC to be database independent.
They can access any database, regardless of the type, vendor,
or format of the database.
JDBC Driver Providers
Many popular databases providers have JDBC drivers that can
be used to access their databases through a Java program.
Available either as downloads or are included in the installation
package of the database.
JDBC Driver Formats
JDBC drivers come in many formats. Some are partially written
in Java and a native language. Others are written entirely in
Java. Regardless of the format, all JDBC drivers contain a Java
class through which you access the driver.
JDBC-ODBC bridge
Since Java cannot communicate directly with the ODBC API, you
The Class.forName() Method
The Class.forName()
This method is a part of JDBC
used to load a JDBC driver from within your program.
A JDBC driver needs to be loaded and registered with the
driver manager before you can use JDBC to access your
database.
JDBC drivers can register themselves, but you need to load the
driver.
This is accomplished by passing the entire class name, including
package, of the JDBC driver class into the Class.forName() method.
Example of the Class.forName() Method
To load the JDBC driver for MS Access, you would use:
Class.forName( "net.ucanaccess.jdbc.UcanaccessDriver" );
The getConnection() Method
After a JDBC driver is loaded, a connection needs to be
established with the database.
This is done via the getConnection() method of the
DriverManager class.
Three different getConnection() methods.
Method Description
getConnection(Stringurl Connects to the database specified by the
) urlparameter. This method assumes the
database does not require a username
and/or password.
getConnection(String Connects to the specified database using
url,Stringuser,String the supplied usernameand password.
password )
getConnection(String Connects to the specified database using
url,Propertiesinfo ) the list of properties specified in the
Propertiesobject. This list of properties
can contain a username and password,
along with any other database-specific
Calling the getConnection()
Method
The Database URL
jdbc:sub-protocol:data-source
jdbc, identifies this URL as a JDBC URL.
sub-protocol, identifies the sub-protocol. This
value will vary based on the driver you are
using (when using the JDBC-ODBC bridge, the
sub-protocol is always odbc)
data-source, specifies the data source to which
you wish to connect. This value will also vary
based on the driver you are using. (created
Bookstore )
jdbc:odbc:Bookstore
The Connection Object
When you invoke the getConnection() method,
the DriverManager class attempts to find an
appropriate driver to connect to the database.
When it finds one, a new Connection object is

created and returned to you.


Example:
Connection conn =
DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\k
adriu\\Desktop\\Universum\\Databazat\\bookstore.mdb" );
The Connection Interface
Methods
Method Description
close() Closes the connection to the database and releases
any resources used by the connection.
commit() If the connection does not perform an autocommit
when you modify the database, this method will
commit your changes. This method is the opposite of
the rollback()method.
createStatement() Creates and returns to you a Statementobject that is
used to send SQL statements to the database.
getAutoCommit() Returns trueif the connection is performing an
autocommit, otherwise returns false.
getMetaData() Returns a DatabaseMetaDataobject that can be used
to obtain information about the database.
isClosed() Returns trueif the connection is open, false
otherwise.
The Connection Interface
Methods
Method Description
isReadOnly() Returns trueif the connection is read-only, false
otherwise.
prepareCall() Allows you to access stored procedures in the
database. Returns a CallableStatementobject.
prepareStatement() Allows you to send parameterized SQL statements to
the database. Returns a PreparedStatementobject.

rollback() If the connection does not perform an autocommit


when you modify the database, this method will undo
all of your changes since the last time you called
commit(). This method is the opposite of the
commit()method.
setAutoCommit() Allows you to turn autocommit on or off.
setReadOnly() Allows you to enable or disable read-only mode.
Autocommit Transaction
Autocommit transaction is a JDBC feature that allows a
database to be updated after every SQL statement is
executed. When you first establish a connection,
autocommit is enabled by default. You can enable and
disable autocommit by using the setAutoCommit() method
of the Connection object.
The commit() Method
With autocommit enabled, every change you make to the
database is permanent. When autocommit is disabled,
you will need to use the commit() method to make your
changes permanent.
The rollback() Method
The rollback() method allows you to undo all your
changes, and revert the database to the point when it was
last committed. You can only use the rollback() method
when autocommit is disabled.
The close() Method
The close() Method
The close() method allows you to close the
connection by yourself. Connections to a
database are automatically closed when the
Connection object is garbage collected, either
because the program exits or when the object is
no longer being referenced.
An example of using the Close() method is:
Connection conn;
...
// close the connection object
conn.close();
The createStatement() Method
The createStatement() method returns a
Statement object stored in a variable.
Statement stmt = conn.createStatement();

Method Used to
executeUpdat Issue an SQL statement to the database that
e() modifies the database in some way. This method
should be used for INSERT, UPDATE, and DELETE
statements.
executeBatch Process multiple SQL statements that update the
() database.
executeQuery Query the database using a SELECTstatement.
() This method returns a ResultSetobject.

execute() Process an SQL statement that can return multiple


results. Can be used for updates and queries.
The executeUpdate() Method
This method takes one parameter, which is the
SQL statement that you want to execute, and
returns the number of rows that were updated as a
result of the update.
Example of the executeUpdate() Method
Connection conn;
...
Statement stmt = conn.createStatement();
String updateStatement = "INSERT INTO AUTHORS VALUES
( 54,'Doe','John' );";
// execute the statement
int numRowsUpdated =
stmt.executeUpdate( updateStatement );
Batch Updates
Batch update is used to execute several
update statements concurrently.
You use the addBatch() method to add SQL
statements to the batch.
When ready, you call the executeBatch() method
to execute all the statements in the batch.
The executeBatch() method returns an array of
integers. Each integer in the array corresponds
with an SQL statement in the batch.
Batch Updates
Return Value Meaning
returnValue The statement executed
>=0 successfully and the return
value represents how many
rows were modified during the
update.
returnValue The statement was executed
==2 successfully, but the number of
modified rows is not known.
returnValue The statement did not execute
==3 successfully.
Batch Updates
The code segment demonstrates the syntax
of batch statements:
Connection conn;
...
Statement stmt = conn.createStatement();
// add statements to the batch
stmt.addBatch( ... );
stmt.addBatch( ... );
stmt.addBatch( ... );
stmt.addBatch( ... );
// execute the batch
int[] results = stmt.executeBatch();
The clearBatch() Method
If, after adding statements to the batch, you decide not to execute
it, you can use the clearBatch() method to remove all the SQL
statements currently in the batch. When you successfully execute
a batch, the batch is cleared for you automatically.
Syntax of Batch Statements
The code segment demonstrates the syntax of batch statements:
Connection conn;
...
Statement stmt = conn.createStatement();
// add statements to the batch
stmt.addBatch( ... );
stmt.addBatch( ... );
stmt.addBatch( ... );
stmt.addBatch( ... );
// execute the batch
int[] results = stmt.executeBatch();
The executeQuery() Method
You use the executeQuery() method to obtain
information from the database using a SELECT
statement.
takes one parameter, the SQL statement that you want to
execute.
differs from the executeUpdate() method in that it returns a
ResultSet object instead of an int.
Example of the executeQuery Statement
Connection conn;
...
Statement stmt = conn.createStatement();
String queryStatement = "SELECT * from Titles;";
// execute the statement
ResultSet rs = stmt.executeQuery( queryStatement );
The ResultSet Object
When you query a database using the
executeQuery() method, a ResultSet object is
returned.
Gives access to the result set created by the
database in response to a query.
If a result set is a table with rows and columns,
each row represents one record, or result, to
your query.
When processing a result set, you will typically
process each record, one at a time, until there
are no records left.
Navigation Through the
ResultSet
Every result set has a cursor that points to the
current record.
Use the next() method of the ResultSet object to
move to the next record in the result set
Navigation Through the
ResultSet
The first call to next() points the cursor to
the first record of the result set.
The next() method will continue to return
true until there are no more records in the
result set.
For example:
ResultSet rs =
stmt.executeQuery( queryStatement );
while( rs.next() ) {
// process the current record
}
The get() Method
When the cursor is pointing to a record in the result set, you
can access the columns of that record.
This is done by using the get() methods defined in the
ResultSet interface.
Some of the get() methods available from a ResultSet object
are:
getBoolean()
getDate()
getDouble()
getFloat()
getInt()
getLong()
getObject()
getString()
getTimeStamp()
Example of the get() Method
When one of the get() methods is called, you
need to specify a column in the result set. This
can be done in one of two ways.
The first is to specify a column by name. For example:
// get the author's first name
String firstName = rs.getString( "AuthFirst" );
The other option is to specify a column by number.
Result set columns in JDBC are one-based, meaning they
start at 1, not 0. If you wanted to retrieve data from the
third column in your result set, you could use the code:
// get the data from the third column
String firstName = rs.getString( 3 );
The Result Set Metadata
JDBC provides a mechanism for obtaining information about a
result sets columns.
This information is called result set metadata and is useful when
you are unfamiliar with the data being returned from a query.
This information includes the number of columns, type of
columns, and the column names of the result set.
To obtain this information, you can use the getMetaData()
method of the result set.
This will return a ResultSetMetaData object.(The row information
of a result set is not available via result set metadata.)
Some of the commonly used methods of the ResultSetMetaData
interface are getColumnCount(), getColumnName, and
getColumnType.
The Result Set Metadata

Method Description

getColumnCount() Returns the number of


columns in the result set.
getColumnName(column) Returns the name of the
specified column.
getColumnType(column) Returns the data type of the
specified column.

Example of the Result Set Metadata


ResultSetMetaData metadata = rs.getMetaData();
The ResultSetMetaData
Interface Methods
Using the getColumnCount(),
getColumnName( column ), and
getColumnType( column ) methods, you can
create a very dynamic program that can
process a result set without knowing how
many columns there are or what the
columns names are.
Procedure Reference: Query a
Database
1. Open Eclipse, create a project.
2. Add in the path (right click->Build Path->Add external files) 5 .jar files from:
http://ucanaccess.sourceforge.net/site.html
3. Import the java.sql package and define a class with the main() method in it:
DATABASE_URL =
"jdbc:ucanaccess://C:\\Users\\akadriu\\Desktop\\bookstore.mdb
4. Create a static String constant that holds the URL of the database:
5. Create another static String constant that holds the SQL SELECT statement
that need to be executed.
6. Within the main() method, load the JDBC-ODBC bridge driver using the
Class.forName() method wrapped in a try-catch block.
try {
Class.forName( "net.ucanaccess.jdbc.UcanaccessDriver" );
}
catch ( ClassNotFoundException e ) {
System.err.println("Error Message");
}
Procedure Reference: Query a
Database
7. Within another try block, write code to connect to the
database using the getConnection() method of the
DriverManager class and store the Connection object
in a variable.
Connection ConnectionVariable =
DriverManager.getConnection(DATABASE_URL );
8. Add a catch block to handle the SQL Exception.
9. Obtain a Statement object by using the connections
createStatement() method and store the object in a
variable.
Statement StatementVariable = createStatement();
10. Execute the database query by using the
Statements executeQuery() method and save the
result set that is returned in a variable called
ResultSetVariable.
Procedure Reference: Query a Database
11. Obtain the result set metadata by using the result sets
getMetaData() method and save the ResultSetMetaData object
in a variable.
ResultSetMetaData ResultSetMetaDataVariable =
rs.getMetaData();
12. Display the SQL query.

System.out.println( "Query: " +


DATABASE_QUERY );System.out.println();
13.Create a while loop to loop through the records left in the result
set using the result sets next() method.
while ( ResultSetVariable.next() ) { }
14. Within the while loop, create a for loop that uses the result set
metadata to iterate through all the columns of the result set.
15. Within the for loop, obtain the current columns name by using
the metadatas getColumnName() method.
String ColumnNameVariable =

ResultSetMetaDataVariable.getColumnName( ColumnNumberV
Procedure Reference: Query a
Database
16. Obtain the current columns value by using the result
sets getString() method.
String ColumnValueVariable =
ResultSetVariable.getString(ColumnNumberVariable );
17. Output the current columns name and value separated
by a colon.
System.out.println( ColumnNameVariable + ": " +
ColumnValue );
18. A transaction can be temporarily stored in a buffer and
can either be committed using the statement
Connectionobject.commit(); or rolled back using the
statement Connectionobject.rollback();
19. Compile, run, and observe the output of the program.
Closing ResultSet and
Statement Objects
An example for closing the result set is:
ResultSet rs;
...
// close the result set
rs.close();
An example for closing the Statement object is:
Statement stmt = conn.createStatement();
...
// close the statement object
stmt.close();
Both ResultSet and Statement objects will be closed
automatically by JDBC if you do not close them. However,
closing them yourself will assure that any system resources
used by these objects will be released immediately.