Professional Documents
Culture Documents
14 Java Database Connectivity
14 Java Database Connectivity
14 Java Database Connectivity
IVX. Java Database Connectivity (JDBC)
Objectives
To understand the relational database model.
To use the classes and interfaces of the java.sql package to query a database, insert data
into a database and update data in a database.
To understand basic database queries using Structured Query Language (SQL).
Introduction
A database is an organized collection of data. There are many different strategies for
organizing data to facilitate easy access and manipulation. A database management system
(DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many
users. Database management systems allow for the access and storage of data without concern
for the internal representation of data.
Today’s most popular database systems are relational databases, where the data is
stored without consideration of its physical structure. A language called SQL—pronounced
“sequel,” or as its individual letters—is the international standard language used almost
universally with relational databases to perform queries (i.e., to request information that
satisfies given criteria) and to manipulate data.
Advantages of Database Systems
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standards can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirements can be balanced.
In non‐database systems, each distinct application maintains its own files, often with
considerable redundancy and a variety of physical formats. In database, redundancy is reduced
by integrating separate files.
Sharing is one of the most important benefits of database systems. Existing applications
can reference the same data.
Centralized control makes it possible to enforce standards rigidly. This becomes
particularly important in computer networks in which data migration between systems occurs.
Training‐workshop on Object‐oriented Programming using Java
162 | P a g e
Security is an intriguing issue in database systems. The data may actually be more at risk
because it is collected and retained in a central location rather than being dispersed throughout
physically separate files in many locations. To counter this, database systems must be designed
with elaborate access controls.
Data Independence
One of the most important aspects of database systems is data independence (i.e.
applications need not be concerned with how the data is physically stored or accessed). An
application is said to be data dependent if the storage structure and accessing strategy cannot
be changed without affecting the application significantly.
Data independence makes it convenient for various applications to have different views
of the same data. From the system’s standpoint, data independence makes it possible for the
storage structure and accessing strategy to be modified in response to the installation’s
changing requirements, but without the need to modify functioning applications.
Distributed Database
A distributed database is a database that is spread across the computer systems of a
network. Ordinarily in such systems each data item is stored at the location which it is most
frequently used, but it remains accessible to other network users.
Distributed systems provide the control and economics of local processing with the
advantages of information accessibility over a geographically dispersed organization. They can
be costly to implement and operate, however, and they can suffer from increased vulnerability
to security violations.
Relational Database
Three database models have achieved widespread popularity: hierarchical, network and
relational. In this course, we will concentrate on the popular of these models – the relational
database model.
A relational database is a logical representation of data that allows the data to be
accessed without consideration of its physical structure. A relational database stores data in
tables. The figure below illustrates a sample table that might be used in a personnel system.
The table name is EMPLOYEE, and its primary purpose is to store the attributes of an employee.
Tables are composed of rows, and rows are composed of columns in which values are stored.
Any particular row of the table is called a record. This table consists of six rows. The Number
column of each row in this table is the table’s primary key—a column (or group of columns) in a
table with a unique value that cannot be duplicated in other rows. This guarantees that each
row can be identified by its primary key. Good examples of primary key columns are a social
security number, an employee ID number and a part number in an inventory system, as values
in each of these columns are guaranteed to be unique.
Training‐workshop on Object‐oriented Programming using Java
163 | P a g e
Each column of the table represents a different field. Records are normally unique (by
primary key) within a table, but particular field values may be duplicated between records. For
example, three different records in table EMPLOYEE contain department number 413.
Different users of a database are often interested in different data items and different
relationships between those data items. Some users want only certain subsets of the table
columns. Other users of a database wish to combine smaller tables into larger ones to produce
more complex tables. The subset operation is called projection and the combination operation
is join.
For example, we might use the projection operation to create a new table called
DEPARTMENT‐LOCATOR whose purpose is to show where departments are located. This new
table is manipulated as a ResultSet object.
The relational database organization has many advantages over the hierarchical and
network schemes.
1. The tabular representation used in the relational scheme is easy for users to
comprehend and easy to implement in the physical database system.
2. It is relatively easy to convert virtually any other type of database structure into
relational scheme. Thus, the scheme may be viewed as a universal form of
representation.
3. The projection and join operations are easy to implement and make it easy to create the
new tables needed for particular applications.
4. Searches in a database can be faster than in schemes that require following series of
pointers.
5. Relational structures are easier to modify than hierarchical or network structures. In
environments where flexibility is important, this becomes critical.
6. The clarity and visibility of the database improve with the relational structure. It is much
easier to search tabular data than it is to unwind possibly arbitrarily complex
interconnections of data elements in a pointer‐based mechanism.
Structured Query Language
Structured Query Language (SQL) is a widely‐used query language designed for
managing data in relational database management systems (RDBMS). Originally based
upon relational algebra and tuple relational calculus, its scope includes data insert,
query, update and delete, schema creation and modification, and data access control.
Queries
The most common operation in SQL is the query, which is performed with the
declarative SELECT statement. SELECT retrieves data from one or more tables, or expressions.
Standard SELECT statements have no persistent effects on the database. Some non‐standard
implementations of SELECT can have persistent effects, such as the SELECT INTO syntax that
exists in some databases.
Training‐workshop on Object‐oriented Programming using Java
164 | P a g e
Queries allow the user to describe desired data, leaving the database management
system (DBMS) responsible for planning, optimizing, and performing the physical operations
necessary to produce that result as it chooses.
A query includes a list of columns to be included in the final result immediately following
the SELECT keyword. An asterisk ("*") can also be used to specify that the query should return
all columns of the queried tables. SELECT is the most complex statement in SQL, with optional
keywords and clauses that include:
The FROM clause which indicates the table(s) from which data is to be retrieved.
The FROM clause can include optional JOIN sub clauses to specify the rules for joining
tables.
The WHERE clause includes a comparison predicate, which restricts the rows returned
by the query. The WHERE clause eliminates all rows from the result set for which the
comparison predicate does not evaluate to True.
The GROUP BY clause is used to project rows having common values into a smaller set
of rows. GROUP BY is often used in conjunction with SQL aggregation functions or to
eliminate duplicate rows from a result set. The WHERE clause is applied before
the GROUP BY clause.
The HAVING clause includes a predicate used to filter rows resulting from the GROUP
BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions
can be used in the HAVING clause predicate.
The ORDER BY clause identifies which columns are used to sort the resulting data, and
in which direction they should be sorted (options are ascending or descending). Without
an ORDER BY clause, the order of rows returned by an SQL query is undefined.
The SELECT Query
A typical SQL query “selects” information from one or more tables in a database. Such
selections are performed by SELECT queries. The simplest form of a SELECT query is
SELECT * FROM TableName
In the example above, the asterisk (*) indicates that all row and columns from
TableName should be selected and TableName specifies the table in the database from which
the data will be selected.
To select specified fields from a table, replace the asterisk (*) with a comma‐separated
list of field names to select.
SELECT field1, field2 FROM TableName
The WHERE Clause
Often it is necessary to locate records in a database that satisfy certain selection criteria.
Only records that match the selection criteria are actually selected. SQL uses the optional
Training‐workshop on Object‐oriented Programming using Java
165 | P a g e
WHERE clause in a SELECT query to specify the selection criteria for the query. The simplest
format of SELECT query with selection criteria is
SELECT * FROM TableName WHERE criteria
The WHERE clause condition can contain operators <, >, <=, >=, =, <> and LIKE. Operator
LIKE is used for pattern matching with wildcard characters asterisk (*) and question mark (?).
Pattern matching allows SQL search for similar strings. An asterisk (*) in the pattern indicates
any number of characters in a row at the asterisk’s location in the pattern. A question mark (?)
in the pattern string indicates a single character at the position in the pattern.
A query can be specialized to allow any character in a range of characters in one
position of the pattern string. A range of characters can be specified as follows
[startValue‐endValue]
Where startValue indicates the first character in the range and endValue represents the
last value in the range.
The ORDER BY Clause
The results of a query can be arranged in ascending or descending order using the
optional ORDER BY clause. The simplest form of an ORDER BY clause is
SELECT * FROM TableName ORDER BY field ASC
SELECT * FROM TableName ORDER BY field DESC
Where ASC specifies ascending (lowest to highest) order, DESC specifies descending
(highest to lowest) order and field represents the field that is used for sorting purposes.
Using INNER JOIN
Often it is necessary to merge data from multiple tables into a single view for analysis
purposes. This is referred to as joining the tables and is accomplished using the INNER JOIN
operation in the FROM clause of a SELECT query. An INNER JOIN merges records from two or
more tables by testing for matching values in a field that is common to both tables. The
simplest format of an INNER JOIN clause is
SELECT * FROM Table1 INNER JOIN Table2 ON Table1.field = Table2.field
The ON part of the INNER JOIN clause specifies the fields from each table that should be
compared to determine which records will be selected.
Training‐workshop on Object‐oriented Programming using Java
166 | P a g e
Registering your database as an ODBC Data Source
The preceding example assumes that the database usedsa is already registered as an
ODBC data source. This section illustrates how to set up an ODBC source in a Microsoft
Windows computer. Note: The computer must have Microsoft Access installed. To connect to
the database, an ODBC data source must be registered with the system through the ODBC Data
Sources option in the Windows Control Panel. Double click this option to display the ODBC
Data Source Administrator.
This dialog is used to register our User Data Source Name (User DSN). Make sure that
the User DSN tab is selected, and then click Add to display the Create New Data Source dialog.
Because we are using Microsoft Access database, we select Microsoft Access Driver and click
Finish.
The ODBC Microsoft Access 97 Setup dialog now appears. We enter the name that we
will use to reference the database with JDBC in the Data Source Name text field. You can also
enter a description of the database. Click the Select button to display the Select Database
dialog. Use this dialog to locate and select the database file on your system (or the network).
When you are done click OK to dismiss the Select Database dialog and return to the ODBC
Microsoft Access 97 Setup dialog. Next click Advanced button to display the Set Advanced
Options dialog. Type the username “anonymous” and password “guest” in the fields at the top
of the dialog, and then click OK to dismiss the dialog. Click OK to dismiss the Microsoft Access
97 Setup dialog.
Notice that the ODBC Data Source Administrator dialog now contains the Data Source
Name you created with your database. Clicking OK dismisses the dialog. We are now ready to
access the ODBC data source through JDBC‐to‐ODBC bridge driver.
A First Example
In this example, we perform a single query on the Teachers.mdb database that stores
data to be displayed in a JTable component. Figure 10.22 shows the table displayed after the
execution of the query.
Example:
Figure 10.22: A JTable showing data from Teachers.mdb database
Training‐workshop on Object‐oriented Programming using Java
167 | P a g e
Code:
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
@SuppressWarnings("unchecked") public class TableDisplay extends JFrame
{
Connection cnnct;
JTable tbl1;
Statement stmnt;
ResultSet results;
@SuppressWarnings("unchecked") public TableDisplay()
{
String url = "jdbc:odbc:Teachers";
String uname="", pwd="";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cnnct = DriverManager.getConnection(url,uname,pwd);
}
catch(ClassNotFoundException cnfex)
{
System.err.println("Failed to load JDBC/ODBC
driver..");
cnfex.printStackTrace();
System.exit(1);
}
catch(SQLException sqlex)
{
System.err.println("Unable to connect!");
sqlex.printStackTrace();
System.exit(1);
}
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
getTable();
JScrollPane scroller = new JScrollPane(tbl1);
c.add(scroller);
pack();
setVisible(true);
}
@SuppressWarnings("unchecked") public void getTable()
{
try
{
String query="SELECT * FROM users";
stmnt = cnnct.createStatement();
Training‐workshop on Object‐oriented Programming using Java
168 | P a g e
results = stmnt.executeQuery(query);
displayResultSet(results);
stmnt.close();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
}
@SuppressWarnings("unchecked") public void
displayResultSet(ResultSet rs) throws SQLException
{
boolean moreRecords = rs.next();
if(!moreRecords)
{
JOptionPane.showMessageDialog(null,"No Records!");
return;
}
Vector columnHeads = new Vector();
Vector rows = new Vector();
try
{
ResultSetMetaData rsmd = rs.getMetaData();
for(int x=2;x<=rsmd.getColumnCount();++x)
{
columnHeads.addElement(rsmd.getColumnName(x));
}
do
{
rows.addElement(getNextRow(rs,rsmd));
}while(rs.next());
tbl1 = new JTable(rows, columnHeads);
validate();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
}
@SuppressWarnings("unchecked") public Vector getNextRow(ResultSet
rs, ResultSetMetaData rsmd) throws SQLException
{
Vector currentRow = new Vector();
for(int x=2;x<=rsmd.getColumnCount();++x)
{
currentRow.addElement(rs.getString(x));
}
return currentRow;
}
public void shutDown()
{
try
{
Training‐workshop on Object‐oriented Programming using Java
169 | P a g e
cnnct.close();
}
catch(SQLException sqlex)
{
System.err.println("Unable to disconnect!");
sqlex.printStackTrace();
}
}
public static void main(String args[])
{
final TableDisplay app = new TableDisplay();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
app.shutDown();
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
}
Reading, Inserting and Updating a Microsoft Access Database
Example: Adding a record to the database
Figure 11.2: A JTable showing data from Teachers.mdb database before adding a record
Training‐workshop on Object‐oriented Programming using Java
170 | P a g e
Figure 11.3: A JTable showing data from Teachers.mdb database after adding a record
Code:
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
@SuppressWarnings("unchecked") public class AddExample extends JFrame
{
Container c = getContentPane();
Connection cnnct;
JTable tbl1;
JScrollPane scroller = new JScrollPane(tbl1);
Statement stmnt;
ResultSet results;
JPanel pnl1 = new JPanel();
JLabel lblFName = new JLabel("First Name:");
JLabel lblLName = new JLabel("Last Name:");
JLabel lblAge = new JLabel("Age:");
String query="SELECT * FROM users";
JButton btnShow = new JButton("Query All Records");
JButton btnAdd = new JButton("Add Record");
JTextField txtFName = new JTextField("",20);
JTextField txtLName = new JTextField("",20);
JTextField txtAge = new JTextField("",5);
@SuppressWarnings("unchecked") public AddExample()
{
String url = "jdbc:odbc:Teachers";
Training‐workshop on Object‐oriented Programming using Java
171 | P a g e
Training‐workshop on Object‐oriented Programming using Java
172 | P a g e
try
{
ResultSetMetaData rsmd = rs.getMetaData();
for(int x=2;x<=rsmd.getColumnCount();++x)
Training‐workshop on Object‐oriented Programming using Java
173 | P a g e
{
columnHeads.addElement(rsmd.getColumnName(x));
}
do
{
rows.addElement(getNextRow(rs,rsmd));
}while(rs.next());
c = getContentPane();
c.remove(scroller);
tbl1 = new JTable(rows, columnHeads);
scroller = new JScrollPane(tbl1);
c.add(scroller);
c.add(pnl1);
validate();
this.pack();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
}
@SuppressWarnings("unchecked") public Vector getNextRow(ResultSet
rs, ResultSetMetaData rsmd) throws SQLException
{
Vector currentRow = new Vector();
for(int x=2;x<=rsmd.getColumnCount();++x)
{
currentRow.addElement(rs.getString(x));
}
return currentRow;
}
public void shutDown()
{
try
{
cnnct.close();
}
catch(SQLException sqlex)
{
System.err.println("Unable to disconnect!");
sqlex.printStackTrace();
}
}
public static void main(String args[])
{
final AddExample app = new AddExample();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
app.shutDown();
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
Training‐workshop on Object‐oriented Programming using Java
174 | P a g e
Figure 11.4: Searching a record from the database
Training‐workshop on Object‐oriented Programming using Java
175 | P a g e
Figure 11.5: Displaying the record found in textfields
Code:
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
@SuppressWarnings("unchecked") public class FindExample extends JFrame
{
Container c = getContentPane();
Connection cnnct;
JTable tbl1;
JScrollPane scroller = new JScrollPane(tbl1);
Statement stmnt;
ResultSet results;
JPanel pnl1 = new JPanel();
JLabel lblSearchFor = new JLabel("Search For:");
JLabel lblSearchFName = new JLabel("First Name:");
JLabel lblSearchLName = new JLabel("Last Name:");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cnnct = DriverManager.getConnection(url,uname,pwd);
}
catch(ClassNotFoundException cnfex)
{
System.err.println("Failed to load JDBC/ODBC
driver..");
cnfex.printStackTrace();
System.exit(1);
}
catch(SQLException sqlex)
{
System.err.println("Unable to connect!");
sqlex.printStackTrace();
System.exit(1);
}
setTitle("Java Example");
txtDisplayFName.setEnabled(false);
txtDisplayLName.setEnabled(false);
txtDisplayAge.setEnabled(false);
pnl1.setLayout(new GridLayout(7,2));
pnl1.add(lblSearchFName);
pnl1.add(txtFName);
pnl1.add(lblSearchLName);
pnl1.add(txtLName);
pnl1.add(new JLabel(" "));
pnl1.add(btnSearch);
pnl1.add(lblDisplay);
pnl1.add(new JLabel(" "));
pnl1.add(lblDisplayFName);
pnl1.add(txtDisplayFName);
pnl1.add(lblDisplayLName);
pnl1.add(txtDisplayLName);
pnl1.add(lblDisplayAge);
pnl1.add(txtDisplayAge);
getTable(query);
c.add(scroller);
c.add(pnl1);
pack();
Training‐workshop on Object‐oriented Programming using Java
177 | P a g e
setVisible(true);
}
c = getContentPane();
c.remove(scroller);
tbl1 = new JTable(rows, columnHeads);
scroller = new JScrollPane(tbl1);
c.add(scroller);
c.add(pnl1);
validate();
this.pack();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
Training‐workshop on Object‐oriented Programming using Java
178 | P a g e
}
@SuppressWarnings("unchecked") public Vector getNextRow(ResultSet
rs, ResultSetMetaData rsmd) throws SQLException
{
Vector currentRow = new Vector();
for(int x=2;x<=rsmd.getColumnCount();++x)
{
currentRow.addElement(rs.getString(x));
}
return currentRow;
}
public void getResults(ResultSet rs)
{
try
{
rs.next();
int recordNumber = rs.getInt(1);
if(recordNumber != 0)
{
txtDisplayFName.setText(rs.getString(2));
txtDisplayLName.setText(rs.getString(3));
txtDisplayAge.setText(rs.getString(4));
}
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
JOptionPane.showMessageDialog(null,"No Record
Found!");
}
}
public void shutDown()
{
try
{
cnnct.close();
}
catch(SQLException sqlex)
{
System.err.println("Unable to disconnect!");
sqlex.printStackTrace();
}
}
public static void main(String args[])
{
final FindExample app = new FindExample();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
app.shutDown();
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
Training‐workshop on Object‐oriented Programming using Java
179 | P a g e
Figure 11.6: Displaying the record found in textfields to be updated
Training‐workshop on Object‐oriented Programming using Java
180 | P a g e
Figure 11.7: Updating and displaying updated records
Code:
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
@SuppressWarnings("unchecked") public class UpdateExample extends JFrame
{
Container c = getContentPane();
String temp1="";
String temp2="";
Connection cnnct;
JTable tbl1;
JScrollPane scroller = new JScrollPane(tbl1);
Statement stmnt;
ResultSet results;
JPanel pnl1 = new JPanel();
JLabel lblSearchFor = new JLabel("Search For:");
JLabel lblSearchFName = new JLabel("First Name:");
JLabel lblSearchLName = new JLabel("Last Name:");
setTitle("Java Example");
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
//c.setLayout(new GridLayout(5,0));
ButtonHandler btnhndler = new ButtonHandler();
btnSearch.addActionListener(btnhndler);
btnUpdate.addActionListener(btnhndler);
btnCancel.addActionListener(btnhndler);
pnl1.setLayout(new GridLayout(8,2));
pnl1.add(lblSearchFName);
pnl1.add(txtFName);
pnl1.add(lblSearchLName);
pnl1.add(txtLName);
pnl1.add(new JLabel(" "));
pnl1.add(btnSearch);
pnl1.add(lblDisplay);
pnl1.add(new JLabel(" "));
pnl1.add(lblDisplayFName);
pnl1.add(txtDisplayFName);
pnl1.add(lblDisplayLName);
pnl1.add(txtDisplayLName);
pnl1.add(lblDisplayAge);
Training‐workshop on Object‐oriented Programming using Java
182 | P a g e
pnl1.add(txtDisplayAge);
pnl1.add(btnCancel);
pnl1.add(btnUpdate);
getTable(query);
c.add(scroller);
c.add(pnl1);
//setSize(400,200);
pack();
setVisible(true);
}
c = getContentPane();
c.remove(scroller);
Training‐workshop on Object‐oriented Programming using Java
183 | P a g e
Training‐workshop on Object‐oriented Programming using Java
184 | P a g e
}
}
public static void main(String args[])
{
final UpdateExample app = new UpdateExample();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
app.shutDown();
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
Training‐workshop on Object‐oriented Programming using Java
185 | P a g e
}
stmnt.close();
txtFName.setText("");
txtLName.setText("");
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
}
else if(e.getSource()==btnCancel)
{
temp1 = "";
temp2 = "";
txtFName.setText("");
txtLName.setText("");
txtDisplayAge.setText("");
txtDisplayFName.setText("");
txtDisplayLName.setText("");
}
}
}
}
Figures 11.2 – 11.7 shows an application that enables the user to add, find and update from a registered
JDBC database, in this example a Microsoft Access database. Notic the @SuppressWarnings statement,
it is an annotation to suppress warnings generated by the code when using generic and/or deprecated
code. A separate topic is used to discuss the Generic classes of Java which is not covered by this training
manual.
Training‐workshop on Object‐oriented Programming using Java