MELJUN CORTES Advanced prog. java ou module 8
-
Upload
meljun-cortes -
Category
Technology
-
view
30 -
download
1
Transcript of MELJUN CORTES Advanced prog. java ou module 8
MODULE 8 JAVA DATABASE CONNECTIVITY
LESSON 8 JAVA DATABASE CONNECTIVITY
Leaning Objectives:
Keywords and Phrases
LEARNER
Advanced Programming Page 1
JDBC ResultSetConnection String Data SourceExecuteQuery
When you finish this lesson, you will be able to do the following:
Connect to a database using JDBC and perform a simple query.
Update relational data using JDBC to execute updates, inserts, and deletes.
Use callable statements to access database procedures.
Use commit, rollback, and savepoint to build transactional systems.
Submit the proposal for Final Project involving Transactional Processing Application.
INTRODUCTION
JDBC is Java application programming interface that allows the Java
programmers to access database management system from Java code. It was
developed by JavaSoft, a subsidiary of Sun Microsystems.
DATABASE CONNECTIVITY
Java Database Connectivity in short called as JDBC. It is a java API which enables
the java programs to execute SQL statements. It is an application programming
interface that defines how a java programmer can access the database in tabular
format from Java code using a set of standard interfaces and classes written in the Java
programming language.
JDBC has been developed under the Java Community Process that allows multiple
implementations to exist and be used by the same application. JDBC provides methods
for querying and updating the data in Relational Database Management system such as
SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically
loading the correct Java packages and drivers and registering them with the JDBC
Driver Manager that is used as a connection factory for creating JDBC connections
which supports creating and executing statements such as SQL INSERT, UPDATE and
DELETE. Driver Manager is the backbone of the jdbc architecture.
Generally all Relational Database Management System supports SQL and we all know
that Java is platform independent, so JDBC makes it possible to write a single database
application that can run on different platforms and interact with different Database
Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is
used for accessing and managing database, but the difference is that JDBC is designed
specifically for Java programs, whereas ODBC is not depended upon any language.
Advanced Programming Page 2
In short JDBC helps the programmers to write java applications that manage these
three programming activities:
1. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of
answering to your query.
JDBC is an API specification developed by Sun Microsystems that defines a uniform
interface for accessing various relational databases. JDBC is a core part of the Java
platform and is included in the standard JDK distribution.
The primary function of the JDBC API is to provide a means for the developer to issue
SQL statements and process the results in a consistent, database-independent manner.
JDBC provides rich, object-oriented access to databases by defining classes and
interfaces that represent objects such as:
1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Binary Large Objects (BLOBs)
7. Character Large Objects (CLOBs)
8. Callable statements
9. Database drivers
10.Driver manager
The JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager
ensures that the correct driver is used to access each data source. The Driver Manager
Advanced Programming Page 3
is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Understanding Connection Object
A Connection object represents a connection with a database. When we connect to a
database by using connection method, we create a Connection Object, which
represents the connection to the database. An application may have one or more than
one connections with a single database or many connections with the different
databases also.
We can use the Connection object for the following things:
1). It creates the Statement, PreparedStatement and CallableStatement objects for
executing the SQL statements.
2). It helps us to Commit or roll back a jdbc transactionn.
3). If you want to know about the database or data source to which you are connected
then the Connection object gathers information about the database or data source by
the use of DatabaseMetaData.
4). It helps us to close the data source. The Connection.isClosed() method returns true
only if the Connection.close() has been called. This method is used to close all the
connection.
Firstly we need to to establish the connection with the database. This is done by using
the method DriverManager.getConnection(). This method takes a string containing a
URL. The DriverManager class, attempts to locate a driver that can connect to the
database represented by the string URL. Whenever the getConnection() method is
called the DriverManager class checks the list of all registered Driver classes that can
connect to the database specified in the URL.
Advanced Programming Page 4
Syntax:
String url = "jdbc: odbc: makeConnection";
Connection con = DriverManager.getConnection(url, "userID", "password");
Basic steps in writing a JDBC Application
This section gives you brief description of JDBC Steps for making connection with the
database, executing the query and showing the data to the user. In this application we
have connected to the MySQL database and retrieved the employee names from the
database. Here are the JDBC Steps to be followed while writing JDBC program:
Loading Driver
Establishing Connection
Executing Statements
Getting Results
Closing Database Connection
Let us now examine the basic steps required in all Java programs to handle JDBC.
Step 1: Loading Drivers
First, you have to load the appropriate driver. You can use one driver from the available
four. However, the JDBC-ODBC driver is the most preferred among developers. In
order to load the driver, you have to give the following syntax:
Class.ForName("sun.jdbc.odbc.JdbcOdbcDriver");
Step 2: Making a Connection
The getConnection() method of the Driver Manager class is called to obtain the
Connection object. The syntax looks like this:
Connection conn = DriverManager.getConnection("jdbc:odbc:<DSN NAME>");
Advanced Programming Page 5
Here, note that getConnection() is a static method, meaning it should be accessed
along with the class associated with the method. You have to give the Data Source
Name as a parameter to this method. (See section below for setting up the Data Source
Name in your computer.)
Step 3: Creating JDBC Statements
A Statement object is what sends your SQL Query to the Database Management
System. You simply create a statement object and then execute it. It takes an instance
of active connection to create a statement object. We have to use our Connection object
"conn" here to create the Statement object "stmt". The code looks like this:
Statement stmt = conn.createStatement();
Step 4: Executing the Statement
In order to execute the query, you have to obtain the Result Set object (similar to
Record Set in Visual Basic) and a call to the executeQuery() method of the Statement
interface. You have to pass a SQL query like select * from students as a parameter to
the executeQuery() method. If your table name is different, you have to substitute that
name in place of students. Actually, the RecordSet object contains both the data
returned by the query and the methods for data retrieval.
The code for the above step looks like this:
ResultSet rs = stmt.executeQuery("select * from students");
If you want to select only the name field, you have to issue a SQL command like Select Name from Student. The executeUpdate() method is called whenever there is a
delete or an update operation.
Advanced Programming Page 6
Step 5: Looping Through the ResultSet
The ResultSet object contains rows of data that is parsed using the next() method, such
as rs.next(). We use the getXXX() method of the appropriate type to retrieve the value
in each field. For example, if your first field name is ID, which accepts Number values,
then the getInt() method should be used. In the same way, if the second field Name
accepts integer String values, then the getString() method should be used, like the
code given below:
System.out.println(rs.getInt("ID"));
Step 6: Closing the Connection and Statement Objects
After performing all the above steps, you have to close the Connection and RecordSet
objects appropriately by calling the close() method. For example, in our code above, we
will close the object as conn.close()and statement object as stmt.close().
The code for the sample program is shown below for your reference:
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SampleDBConnection extends JFrame implements ActionListener {
JTextField idNo;
JTextField studentName;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;
Advanced Programming Page 7
public SampleDBConnection() {
super("My Students");
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));
id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next");
p = new JPanel();
c.add(new JLabel("Student ID",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Student Name",JLabel.CENTER));
c.add(name);
c.add(p);
p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());
}
public static void main(String args[]) {
SampleDBConnection d = new SampleDBConnection();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:cust");
stat = conn.createStatement();
res = stat.executeQuery("Select * from Students"); // Students is
// the table name
res.next();
}
Advanced Programming Page 8
catch(Exception e) {
System.out.println("Error" +e);
}
d.showRecord(res);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == next) {
try {
res.next();
}
catch(Exception ee) {}
showRecord(res);
}
}
public void showRecord(ResultSet res) {
try {
id.setText(res.getString(1));
name.setText(res.getString(2));
}
catch(Exception e) {}
}//end of the main
//Inner class WIN implemented
class WIN extends WindowAdapter {
public void windowClosing(WindowEvent w) {
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Database","Thanks",
JOptionPane.QUESTION_MESSAGE);
}
} //end of the class
Advanced Programming Page 9
How to Create a Data Source Name
Follow these steps to create a Data Source Name in Windows
Open ODBC 32-bit Icon from the control panel. (Start | Settings)
Click on the Add button and select Microsoft Access Driver.
Select the appropriate driver if you are using other databases.
Enter a name as Data Source Name and browse for your database by clicking
the Select button.
You can also write a short description, but this is optional.
Finally, click on the Finish button.
private static final String accessDBURLSuffix = ";DriverID=22;READONLY=false}";
// Initialize the JdbcOdbc Bridge Driver
static {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(ClassNotFoundException e) {
System.err.println("JdbcOdbc Bridge Driver not found!");
}
}
/** Creates a Connection to a Access Database */
public static Connection getAccessDBConnection(String filename) throws
SQLException {
filename = filename.replace('', '/').trim();
String databaseURL = accessDBURLPrefix + filename + accessDBURLSuffix;
return DriverManager.getConnection(databaseURL, "", "");
}
Advanced Programming Page 10
The next example manipulates a simple AddressDir database that contains one table
Addresses with 11 columns: ID, FirstName, LastName, City, StateOrProvince,
PostalCode, Country, EmailAddress, HomePhone, and FaxNumber. The fields other
than ID are all strings. The program provides facilities for inserting new records,
updating existing records and searching for records in the database.
// Inserting into, updating and searching through a database
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Addresses extends JFrame( )
{
private ControlPanel controls;
private ScrollingPanel scrollArea;
private JTextArea output;
private String url;
private Connection connect;
private JScrollPane textpane;
public Addresses( )\
{
Super(“Address book database application”);
Container c = getContentPane( );
//screen layout
scrollArea = new ScrollingPanel( );
output = new JTextArea(6, 30);
c.setLayout( new BorderLayout( ));
c.add(new JScrollPane(scrollArea), BorderLayout.CENTER);
textpane = new JScrollPane(output);
c.add(textpane, BorderLayout.SOUTH);
Advanced Programming Page 11
//set up database connection
try {
url = “jdbc:odbc:AddressDir”;
Class.forName(“sun.jdbc,odbc,JdbcOdbcDriver”);
Connect = DriverManager.getConnection(url);
Output.append(“Connection successful \n”);
}
catch (ClassNotFoundException cnfex)
{
cnfex.printStackTrace( );
output.append(“Connection Unsuccessful\n” + cnfex.toString( ));
}
controls = new ControlPanel(connect, scrollArea, output);
c.add(controls, BorderLayout.NORTH);
setSize(500,500);
show( );
}
public static void main(String args[ ])
{ Addresses app = new Addresses( );
app.addWindowListener(
new WindowAdapter( ) {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
}
);
} }
Advanced Programming Page 12
// adding record into the table
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AddAddresses implements ActionListener
{
private ScrollingPanel fields;
private JTextArea output;
private Connection connect;
public AddAddresses(Connection c, ScrollingPanel f, JTextArea o)
{
connection = c;
fields = f;
output = o;
}
public void actionPerformed(ActionEvent e)
{
try{
Statement statement = connection.createStatement( );
if ( !fields.last.getText( ).equals( “”) &&
!fields.first.getText( ).equals(“”) )
{
String query = “INSERT INTO Addresses (“ +
“firstname, lastname, address, city, “ +
“stateorprovince”, postalcode, country, “ +
“emailaddress, homephone, faxnumber” +
Advanced Programming Page 13
“ ) VALUES ( ‘ “+
fields.first.getText( ) + “ ‘ , ‘ “ +
fields.last.getText( ) + “ ‘ , ‘ “ +
fields.address.getText( ) + “ ‘ , ‘ “ +
fields.city.getText( ) + “ ‘ , ‘ “ +
fields.state.getText( ) + “ ‘ , ‘ “ +
fields.zip.getText( ) + “ ‘ , ‘ “ +
fields.country.getText( ) + “ ‘ , ‘ “ +
fields.email.getText( ) + “ ‘ , ‘ “ +
fields.home.getText( ) + “ ‘ , ‘ “ +
fields.fax.getText( ) + “ ‘)” ;
output.append(“\nSending query : “+
connection.nativeSQL(query) + “\n”);
int result = statement.executeUpdate(query);
if ( result == 1)
output.append(“\n Insertion Successful\n”);
else {
output.append(“\n Insertion failed\n”);
fields.first.setText(“”);
fields.last.setText(“”);
fields.address.setText(“”);
fields.city.setText(“”);
fields.state.setText(“”);
fields.zip.setText(“”);
fields.country.setText(“”);
fields.email.setText(“”);
fields.home.setText(“”);
fields.fax.setText(“”);
}
}
Advanced Programming Page 14
else {
output.append(“\nEnter at least first and last name then” +
“press Add\n”);
statement.close( );
}
catch(SQLException sqlex) {
sqlex.printStackTrace( );
output.append(sqlex.toString( ) );
}
}
}
Advanced Programming Page 15
Reading Assignment:
E-books
o http://java.sun.com/docs/books/tutorial/
o http://www.java-samples.com/showtutorial.php?tutorialid=293
o http://roseindia.net/jsp/simple-jsp-example/nesting-try.shtml
Exercises/Written Assignments
1. Define Java Database Connectivity
2. Differentiate the following terms:
a) Driver Manager
b) Connection
3. What are the steps in Creating Database Server Name. Be able to
explain each briefly.
4. Determine what SQL command is used in the following Java statements.
a) Create a table in the database named “myTable”.
stmt.executeUpdate(
"______________ myTable(test_id int," + "test_val char(15) not null)");
b) Insert some values into the table.
_________________( "INSERT INTO myTable(test_id, " +
"test_val) VALUES(1,'One')");
c) stmt.executeUpdate( "__________________ myTable(test_id, " +
"test_val) VALUES(2,'Two')");
d) Display URL and connection information
__________________("URL: " + url);
System.out.println("Connection: " + con);
Advanced Programming Page 16
e) Get a Statement object
stmt = con._________________();
Case Problem
1. Design and develop a system in your company applying the database
concepts you learned in this module. Your system will have the
functionality of file maintenance and transaction processing.
References/Bibliography
http://java.sun.com/docs/books/tutorial/
http://www.java-samples.com/showtutorial.php?tutorialid=293
http://roseindia.net/jsp/simple-jsp-example/nesting-try.shtml
http://www.developer.com/java/data/article.php/3417381/Using-JDBC-with-
MySQL-Getting-Started.htm
Advanced Programming Page 17