0% found this document useful (0 votes)
2 views

J2EE notes

Advance java notes bcs

Uploaded by

Jaya laxmi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

J2EE notes

Advance java notes bcs

Uploaded by

Jaya laxmi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

JDBC and Embedded SQL:

Model Programs: There are many styles can be used to write the data access portion of a J2EE
component. The Model A program style is used to execute SQL requests that use the execute ()
or executeUpdate() method and donot return ResultSet. The Model B program style is used to
execute SQL requests that use the executeQuery() method which returns a ResultSet.
Both program styles are designed to minimize the code clutter.
Model A Program:
import java.sql.*;
public class ModelA
{
private Connection database;
private Statement DataRequest;
public ModelA()
{
String url=“”;
String userID=“”;
String password=“”;
try{
Class.forName(“”);
Database=DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error) {
System.err.println(“” + error);
System.exit(1);
}
catch (SQLException error){
System.err.println{“” + error);
If(Database != null){
try{
Databse.close();
}
Catch(SQLException er) {}
}
System.exit(2);
}
try{
// insert example code here
}
catch(SQLException error){
System.err.println(“” + error);
if(Database != null) {
try{
Database.close();
}
catch(SQLException er) {}
}
System.exit(3);
}
if(Database != null){
try{
Database.close();
}
catch(SQLException er){}
}
}
public static void main(String args[])
{
final ModelA sql1=new ModelA();
System.exit(0);
}
}

Model B Programming:
The Model B program is designed for use by J2EE components that retrieve information from a
database. Model B program is similar to the Mode A program in that the constructor definitions
and the main() are identical.
Model B contains DisplayResults() and DownRow(). DisplayResults() is passed the ResultSet
returned in the second try{} block. Which is used to move the virtual cursor to the first row of
the ResultSet using the next() method. The next() returns value of Records and displays a “no
data returned” message if records contains a false value indicating the there is not any data in the
row. DownRow() extracts data from the current row of the ResultSet, control returns to
DisplayResults() where the next() methos is called and the results are evaluated by the do..while
loop is exited and control returns to the constructor.
import java.sql.*;
public class ModelB
{
private Connection Database;
private Statement DataRequest;
private ResultSet Results;
public ModelB()
{
String url=“”;
String userID=“”;
String password=“”;
try{
Class.forName(“”);
Database=DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error) {
System.err.println(“” + error);
System.exit(1);
}
catch (SQLException error){
System.err.println{“” + error);
System.exit(2);
}
try{
// insert example code here
}
catch(SQLException error){
System.err.println(“” + error);
if(Database != null) {
try{
Database.close();
}
catch(SQLException er) {}
}
System.exit(3);
}
if (Database != null){
try{
Database.close();
}
catch(SQLException er){}
}
}
private void DisplayResults(ResultSet DisplayResults) throws SQLException
{
boolean Records=DisplayResults.next();
if(!Records){
System.out.println(“No data returned”);
return;
}
try{
do{
DownRow(DisplayResults);
} while(DisplayResults.next());
}
catch(SQLException error){
System.err.println(“Data display error” + error);
if(Database != null) {
try{
Database.close();
}
catch(SQLException er) {}
}
System.exit(4);
}
}
private void DownRow(ResultSet DisplayResults) throws SQLException
{
//Enter new Downrow() code here
}
public static void main(String args[])
{
final ModelB sql1=new ModelB);
System.exit(0);
}
}

Table:
Tables are database objects that contain all the data in a database. In tables, data is logically
organized in a row-and-column format similar to a spreadsheet. Each row represents a unique
record, and each column represents a field in the record.
Creating a Table:
We can create a table by formatting a SQL query. The query contains the Create Table SQL
statement that contains the name of the table. All sql commands are enclosed in double
quotations and assigned to a String object called query. Next the program creates a SQL
statement using the createStatement() method of the Connection object. This method returns the
handle to the DBMS to the DataRequest object which is an object of the Statement class.
Example:
String query=”create table customeraddress(“+”customernumber integer,”+”customerstreet
char(30),”+”customercity char(30),+”customerzip char(30))”;
DataRequest=Database.createStatment();
DataRequest.execute(query);
DataRequest.close();
}

Dropping Table:
A developer may have the right to remove a table, but this is usually reserved for the
development environment only. Once the table is dropped its not possible to recover the table. In
addition to losing data elements stored in the table, dropping a table may also affect the integrity
of the database and tables that relate to values in the dropped table.
Example:
try{
String query=new String(“Drop table customeraddress”);
DataRequest=Database.createStatement();
DataRequest=execute(query);
DataRequest.close();
}
Art of Indexing:
When records are stored in the primary memory like RAM, accessing them is very easy and
quick. But records are not limited in numbers to store in RAM. They are very huge and we have
to store it in the secondary memories like hard disk. In memory we cannot store records like we
see – tables. They are stored in the form of files in different data blocks. Each block is capable
of storing one or more records depending on its size. When we have to retrieve any required data
or perform some transaction on those data, we have to pull them from memory, perform the
transaction and save them back to the memory.
In order to do all these activities, we need to have a link between the records and the data blocks
so that we can know where these records are stored. This link between the records and the data
block is called index. It acts like a bridge between the records and the data block.
How do we index in a book? We list main topics first and under that we group different sub-topic
right?
We do the same thing in the database too. Each table will have unique column or primary key
column which uniquely determines each record in the table. Most of the time, we use this
primary key to create index. Sometimes, we will have to fetch the records based on other
columns in the table which are not primary key. In such cases we create index on those columns.
Index in databases is the pointer to the block address in the memory. But these pointers are
stored as (column, block_address) format.
Example:
Imagine we have a student table with thousands of records, each of which is 10 bytes long.
Imagine their IDs start from 1 2, 3… and goes on. And we have to search student with ID 678.
In a normal database with no index, it searches the disk block from the beginning till it reaches
678. So the DBMS will reach this record after reading 677*10 = 6770 bytes. But if we have
index on ID column, then the address of the location will be stored as each record as (1,200), (2,
201)… (678, 879) and so on. One can imagine it as a smaller table with index column and
address column. Now if we want to search record with ID 678, then it will search using indexes.
i.e.; here it will traverse only 677*2 = 1354 bytes which very less compared to earlier one. Hence
retrieving the record from the disk becomes faster.
• Most of the cases these indexes are sorted and kept to make searching faster.
• If the indexes are sorted, then it is called as ordered indices.

Types of Indexing:

• Indexing in Database is defined based on its indexing attributes.


• Two main types of indexing methods are:
• Primary Indexing
• Secondary Indexing
• If the index is created on the primary key of the table then it is called as Primary
Indexing.
• The primary keys are unique to each record and it has 1:1 relation between the records, it
is much easier to fetch the record using it.
• These primary key are kept in sorted form which helps in performance of the
transactions.
• The primary indexing is of two types – Dense Index and Sparse Index.
Dense Index:
• Indexing is created for primary key as well as on the columns on which we perform
transactions.
• A user can fire query not only based on primary key column. He can query based on any
columns in the table according to his requirement.
• But creating index only on primary key will not help in this case. Hence index on all the
search key columns are stored. This method is called dense index.
Example:
Student can be searched based on his ID which is a primary key. In addition, we search for
student by his first name, last name, particular age group, residing in some place, opted for some
course etc. That means most of the columns in the table can be used for searching the student
based on different criteria. But if we have index on his ID, other searches will not be efficient.
Hence index on other search columns are also stored to make the fetch faster.
Though it addresses quick search on any search key, the space used for index and address
becomes overhead in the memory. Here the (index, address) becomes almost same as (table
records, address). Hence more space is consumed to store the indexes as the record size
increases.
Sparse Index:
• In order to address the issues of dense indexing, sparse indexing is introduced.
• In this method of indexing, range of index columns store the same data block address.
• When data is to be retrieved, the block address will be fetched linearly till we get the
requested data.
• In above diagram we can see, we have not stored the indexes for all the records, instead
only for 3 records indexes are stored. Now if we have to search a student with ID 102,
then the address for the ID less than or equal to 102 is searched – which returns the
address of ID 100. This address location is then fetched linearly till we get the records for
102. Hence it makes the searching faster and also reduces the storage space for indexes.
• The range of column values to store the index addresses can be increased or decreased
depending on the number of record in the table. The main goal of this method should be
more efficient search with less memory space.
But if we have very huge table, then if we provide very large range between the columns will not
work. We will have to divide the column ranges considerably shorter. In this situation, (index,
address) mapping file size grows like we have seen in the dense indexing.
Secondary Index:
• In this method, the huge range for the columns is selected initially so that the mapping
size of the first level becomes small.
• Then each range is further divided into smaller ranges. The mapping of the first level is
stored in the primary memory, so that address fetch is faster.
• The mapping of the second level and actual data are stored in the secondary memory
(hard disk).
If you want to find the record of roll 111 in the diagram, then it will search the highest entry
which is smaller than or equal to 111 in the first level index. It will get 100 at this level.
Then in the second index level, again it does max (111) <= 111 and gets 110. Now using the
address 110, it goes to the data block and starts searching each record till it gets 111.
This is how a search is performed in this method. Inserting, updating or deleting is also done
in the same manner.
Clustering Index:
A clustered index can be defined as an ordered data file. Sometimes the index is created on non-
primary key columns which may not be unique for each record. In this case, to identify the
record faster, we will group two or more columns to get the unique value and create index out of
them. This method is called a clustering index. The records which have similar characteristics are
grouped, and indexes are created for these group.
Example: suppose a company contains several employees in each department. Suppose we use a
clustering index, where all employees which belong to the same Dept_ID are considered within a
single cluster, and index pointers point to the cluster as a whole. Here Dept_Id is a non-unique
key.
Creating an Index:
An index is created by using the CREATE INDEX statement in the query. Create index
statement contains the name of the index and any modifier that describes to the DBMS the type
of the index that is to be created.
Create Index statement uses the ON clauses to identify the name of the table and the name of the
column whose values is used for the index
Syntax: CREATE INDEX index_name ON table_name (column_name)
Example of creating Index
try
{
String query=“CREATE UNIQUE INDEX CustNum ON Customeraddress(customernumber);
stmt=con.createStatement();
stmt.execute(query);
con.close();
}
Creating Secondary Index:
Secondary Index is created by using the CREATE INDEX statement in a query without the use
of unique modifier. Secondary index can have duplica;te values
Example:
try{
String query=new String(“create Index custzip on customeraddress(customerzip)”);
Stmt=con.createStatement();
Stmt.execute(query);
}
Creating Clustered Index:
A clustered index is an index whose key is created from two or more columns of a table.
try{
String query=“create index cust_name on customers(lastname, firstname)”;
Stmt.execute(query);
Stmt.close();}
Dropping an Index:
An existing index can be removed from the database by using the DROP INDEX statement.
try{
String query=new String(“DROP INDEX custname on customers”);
stmt=con.createStatement();
Stmt.execute(query);
Stmt.close();}
Insert Data into Table:
Inserting Row:
Once a database, tables and indexes are createad, a J2EE component can insert a new row into a
table.
Table structure of Customers:
customerNumber Number
FirstName varchar(50)
lastName varachar(50)
DateOfOrder Date
Syntax to Insert a Row into table
try{
String query =“insert into Customers
(customerNumber,FirstName,lastName,DateOfOrder)values(1,’mary’,’smith’,’10/10/2020’)”;
DataRequest=con.createStatement();
DataRequest.executeUpdate(query);
DataRequest.close();
}
Inserting the System’s Date into a Column
Sometime business rules require that current data be placed into a column of a new row. We can
place the system’s date into a colulmn by calling the CURRENT_DATE function. If we are
using Microsoft Access we use NOW. Oracle uses SYSDATE, DB2 uses CURRENT DATE.
try{
String query =“insert into Customers
(customerNumber,FirstName,lastName,DateOfOrder)values(1,’mary’,’smith’,CURRENT_DAT
E)”;
DataRequest =con.createStatement();
DataRequest.executeUpdate();
DataRequest .close();
}
Inserting the System Time Into a Column:
Call the CURRENT_Time() function wheneve a column requires the current time. The
CURENT_TIME() function is called by he DBMS when the query is processed and returns he
current time of the server.
Example:
try{
String query =“insert into Customers (customerNumber,FirstName,lastName,
TimeOfFirstOrder)values(1,’mary’,’smith’,CURRENT_TIME())”;
DataRequst=con.createStatement();
DataRequest.executeUpdate();
DataRequest.close();
}
Inserting a TimeStamp into a column:
A timestamp consist of both the current date and time and is used in applications where both date
and time are critical to the operation of the business. We can place he timestamp into a column
by calling he TIMESTAMP() function.
try{
String query =“insert into Customers (customerNumber,FirstName,lastName,
FirstOrder)values(1,’mary’,’smith’,CURRENT_TIMESTAMP())”;
DataRequest=con.createStatement();
DataRequest.executeUpdate();
DataRequest.close();
}
Selecting Data from Table:
Retrieving information from a database is the most frequently used routing of J2EE components
that interact with a database.
Table structure:
Firstname, varchar(50),
LastName varchar(50),
Street varchar(50),
City varchar(50),
State varchar(50),
Zipcode varchar(50);
Selecting all data from a table:
try{
String query=new String(“select firstname,lastname,street, city,state, zipcode from customers”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Private void DownRow(ResultSet DisplayREsults) throws SQLException
{String FirstName=new String();
String LastName=new String();
String Street=new String();
String City=new String();
String State=new String();
String zipcode=new String();
String printrow;
FirstName=DisplayResults.getString(1);
LastName=DisplayResults.getString(2);
Street=DisplayResults.geString(3);
City=DisplayResults.getString(4);
State=DisplayResults.getString(5);
Zipcode=DisplayResults.getString(6);
printrow=FirtstName+””+LastName+””+City+””+State+””+zipcode;
System.out.println(printrow);
Requesting one column:
We can specify a column that we want returned from a table by using the column name in the
select statement.
try{
String query=new String(“select LastName from customers “);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Private void DownRow(ResultSet displayresults) throws SQLException
{String lastname=new String();
lastname=displayresults.getString(1);
System.out.println(lastname);
Requesting Multiple Columns:
Multiple columns can be retrieved by specifying the names of the column in the SELECT
statement.
try{
String query=new String(“select LastName from customers “);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Private void DownRow(ResultSet displayresults) throws SQLException
{ String FirstName=new String();
String LastName=new String();
String printrow;
FirstName=displayresults.getString(1);
LastName=displayresults.getString(2);
printrow=FirstName+””+LastName;
System.out.println(printrow);}
Requesting Rows:
Specific rows can be retrieved from a column by using the WHERE clause in conjunction with
the SELECT statement. The WHERE clause contains an expression that is used by the DBMS to
identify rows that should be returned in the ResultSet.
try{
String query=new String(“select FirstName,LastName,Street,City,State, Zipcode from
customers LastName=’Jones’“);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Requesting Rows and Columns:
A query can select less than all the columns and all the rows of a table by using a combination.
Try{
String query=new String(“select FirstName,LastName from customers where
LastName=’Jones’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
AND, OR and NOT clause:
The here caluse in a select statement can evaluate values in more than one column of a row by
using the AND,OR andNOT clauses to combine expressions in the WHERE clause.
AND clause:
 AND clause is to join two subexpressions together to form one compound expression.
 AND clause tells the DBMS that the boolean value of both subexpressions must be true
for the compound expression to be true.
 If the compound expression is true, then the current row being evaluated by the DBMS is
returned to program.
 AND clause is used in where clause.
try{
String query=new String(“select FirstName, LastName from customers where lanstname=’Jones’
AND FirstName=’Bob’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();}
OR Clause:
 OR clause is used to create a compound expression using two subexpressions nearly
identical to the way the AND clause joins expressions.
 OR clause tells the DBMS that the compound expression evaluates to a Boolean true if
either of the two subexpressions evaluate to a Boolean true.
try{
String query=new String(“select FirstName, LastName from customers where lanstname=’Mary’
OR FirstName=’Bob’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();}
NOT Clause:
 NOT clause reverses the logic of the subexpression contained in the NOT clause.
 If the subexpression evaluates to a Boolean true value, then the NOT clause reverses the
logic return a Boolean false value.
 If the subexpression evaluates to a Boolean false value then the compound expression to
a Boolean value.

try{
String query=new String(“select FirstName, LastName from customers where lanstname=’Mary’
NOT FirstName=’Bob’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Joining Multiple Compound Expression:
• The AND and OR clauses are used to link together two or more subexpressions. This
results in compound expression.
• There can be multiple compound expressions within a WHERE clause expression.
• AND clause has a higher precedence than the OR clause, so the OR clause must be
placed within parenthesis.
• Example:
• Select * from customer where FirstaName=‘bob’and LastName=‘smith AND (Dept=‘42’
OR Dept=‘45’)
Equal and NOT Equal Operators:
• Equal and Not Equal operators are used to determine if the value in the where clause
expression is or is not in the specify column.
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers
where NOT sales=5000”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Private void DownRow(ResultSet displayresults) throws SQLException
{ String FirstName=new String();
String LastName=new String();
String Street=new String();
String City=new String();
String State=new String();
String printrow;
FirstName=displayresults.getString(1);
LastName=displayresults.getString(2);
Street=displayresults.getString(3);
City=displayresults.getString(4);
State=displayresults.getString(5);
printrow=FirstName+””+LastName+””+Street+””+City+””+State;
System.out.println(printrow);
Less Than and Greater Than Operator:
• The less than and greater than operators direct the DBMS to assess whether or not the
value in the specified column of the current row is less than or greater than the value in
the WHERE clause expression.
• The value in a column that equals the value in the WHERE clause expression is evaluated
as a Boolean false.
• The row containing than value is not returned in the ResultSet.
• The value in the column must be less than or greater than, but not equal to the value in
the WHERE clause expression
Example for Less Than:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales<5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Example for Greater Than:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales>5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Less Than Equal to And Greater Than Equal To:
Less Than Equal To and Greater Than Equal To operators include rows that contain the WHERE
clause expression.
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales<=5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Example for Greater Than:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales=>5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
BETWEEN :
• BETWEEN operator is used to define a range of values that is to be used as the value of
the selection expression.
• The range must consist of a sequential series of values such as from 100 to 200.
• The BETWEEN operator must follow the name of the column in the WHERE clause.
• The AND operator is used to join the lower and upper values of he range.
• All the values in the range including first and last values are considered when the DBMS
evaluates the value of the column specified in the selection expression
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales BETWEEN 20000 AND 39999”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
LIKE Operator:
• LIKE operator directs the DBMS to return a row in the ResultSet if a value in a specified
column partially matches the value of the WHERE clause expression.
• The WHERE clause expression must include a character that must be an exact match and
a wildcard character that is used to match any other character.
• Wildcards used with the LIKE operator:
• Underscore(_): A single character wildcard character.
Eg: if we are unsure if the customer last name is Anderson or Andersesn, we use the
underscore in place of the character that is in the question such as Anders_n.
• Percent(%): a multicharacter wildcard used to match any number of characters.
Eg: Smi% is used to match a value of a column where the first three characters are Smi
and any other characters.

Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
LastName LIKE ‘Smi%’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
IS NULL Operator:
• IS NULL operator is used to determine if a specified column does not contain any value.
• We use IS NULL operator whenever we need to identify rows that are missing
information in a column.
• It is important to understand that the number zero or a space are not NULL values.
• Eg: Zero value in the sales column of a table is a real value
• A column that contains space isnot NULL, because a space is a valid ASCII character
• NULL is void of any value and occurs when a row is inserted into a table without having
a value or the value is explicitly set to NULL
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
State is NULL”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
DISTINCT Modifier:
• The select statement returns all the rows in a table unless a where clause is used to
exclude specific rows.
• ResultSet includes duplicate rows unless a primary index is created for the table or only
unique rows are required in the table.
• When we want to exclude all but one copy of a row from the ResultSet we can use
DISTINCT modifier in the select statement.
• The DISTINCT modifier tells eh DBMS not to include duplicate rows in the resultset
Example:
try{
String query=new String(“Select DISTINCT FirstName,LastName,Street,City,State from
customers”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
IN Modifier:
• IN modifier is used to define a set of values used by the DBMS to match values in a
specified column.
• The set can include any number of values and appear in any order.
• The IN modifier is used in the WHERE clause to define the list of values in the set

Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales IN (20000,30000,40000)”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• If any of these three values are found in the sales column of the current row, the row is
returned to the program.
NOT IN Modifier:
• The NOT IN modifier is similar to the IN modifier except in the NOT IN modifier
reverses the logic of the previous selection expression.
• NOT IN modifier identifies a set of values that shoulnot match rows returned to the
program.
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales NOT IN (20000,30000,40000)”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• Here all columns of rows in the customers table where the value of the sales column is
not 20000,30000,40000 are returned in the resultset.
• Rows with sales of 20000,30000,40000 are not returned .
Metadata:
Metadata is data that describes data. Metadata is returned with the ReslutSet object and
can be extracted from the ResultSet object by creating a ResultSetMetaData.
 Metadata in J2EE can be used in J2EE component for various purposes such as to display
the column name of a column and determine the datatype of a column among other
meatadata
Commonly used metadata are :
 Column Name
 Column Number
 Column data type
 Column width

Number of Columns in ResultSet:


• The getMetaData() method is called to extract metadata from the ResultSet.
• The getMeataData() method returns a ResultSetMetaData object
• The ResultSetMetaDataObject contains several methods that are used to cpy specific
metada from the ResultSet.
Example:
Private void DownRow( ResultSet rs) throws SQLException
{
ResultSetMetaData metadata=rs.getMetaData();
String columnType=new String();
String printrow;
columnType=metadata.getColumnTypeName(9);
System.out.println(“ColumnType”+columnType);
}
• getColumnCount() methods is called to retrieve the number of columns contained in the
ResultSet.
Data Type of a Column:
• Retrieving the data type of a column
• getColumnTypeName() method is used to copy the data type from a specific column
Ex:
Private void DownRow( ResultSet rs) throws SQLException
{
ResultSetMetaData metadata=rs.getMetaData();
String columnType=new String();
String printrow;
columnName=metadata.getColumnTypeName(9);
System.out.println(“ColumnType”+columnType);
}
Name of Column:
• Retrieving the column name from the metadata uses a process similar to that used to copy
the data type of a column from the metadata
• getColumnLabel() method is used to copy the column name from a specific column
• The column name is assigned to the String object columnName.
• The number of column in the ResultSet is passed to the getColumnLabel() method
Ex:
Private void DownRow( ResultSet rs) throws SQLException
{
ResultSetMetaData metadata=rs.getMetaData();
String columnName=new String();
String printrow;
columnName=metadata.getColumnLabel(9);
System.out.println(“ColumnName”+columnName);
}
Column Size:
• Column size of a column is also known as column width
• displaysize() represents the number of characters that are necessary to display the
maximum value that might be stored in the column.
• getColumnDisplaySize() is called and passed the number of the column whose display
size is to be retrieved from the RestultSet.
Example:
Private void DownRow( ResultSet rs) throws SQLException
{
ResultSetMetaData metadata=rs.getMetaData();
Int columnwidth;
String printrow;
columnwidth=metadata.getColumnDisplaySize(
System.out.println(“ColumnWidth”+columnwidth);
}
Updating Tables:
 Modifying data in a database is one of the most common functionalities included in every
J2EE component that provides database interactions.
• Update Statement is used to change the value of one or more columns in one or more
multiple rows of a table
• Update statement must contain the name of the table that is to updated an a Set clause.
• The set clause identifies the name of the column and the new value that will be placed
into the column, overriding the current value
try{
String query=new String(“update customer set street=‘5 Main’ where FirstName=‘Bob’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Updating Multiple Rows:
• Multiple rows of a table can be updated by formatting the WHERE clause expression to
include criteria that qualify multiple rows for the update.
• There are four common WHERE clause expressions that are used to update multiple rows
of a table
1. The IN test: the where clause expression contains multiple values in the IN clause that
must match the value in the specified column for the update to occur in the row.
2. IS NULL test: rows that donot have a value in the specified column are updated when the
ISNULL operator used in the WHERE clause expression
3. The comparison test: WHERE clause expression contains a comparison operator that
compares the value in the specified column with a value in the WHERE clause
expression
4. All Rows: a query can direct the DBMS to update a specified column in all rows of a
table by excluding the WHERE clause in the query.
IN Test:
• IN clause provides two or more values that are compared to the value of the designed
column in the IN clause.
• Rows whose column contain one of these values are then updated by the UPDATE
statement
try{
String query=new String(“update customers SET discount=25 where discount IN(12,15) “);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• Here the value of the discount column is changed to 25 if the current value of the
discount column is either 12 or 15.
IS NULL Test:
• IS NULL test evaluates the value of the column designated in the test to determine if the
column is NULL
try{
String query=new String(“update customers SET discount=0 where LastName IS NULL “);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• Here IS NULL test determines if the LastName column is NULL . If so then a zero is
placed in the discount column.
• If not the value of the discount column remains unchanged.
Updating Based on Values in a Column:
• An expression in the WHERE clause can be used to identify rows that are to be updated
by the UPDATE statement.
try{
String query=new String(“update customers SET discount=20 where discount>20“);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Updating Every Row and Multiple Column:
All rows in a table can be updated by excluding the WHERE clause in the UPDATE statement.
try{
String query=new String(“update customers SET discount=0“);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Multiple Columns of rows can be updated simultaneously by specifying the column names and
appropriate values in the SET clause of the query.
try{
String query=new String(“update customers SET discount=12, street=‘jones street where
lastname=‘jones’“);DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Updating Using Calculations:
The value that replaces the current value in a column does not have to be explicitly in the SET
clause if the value can be derived from a value in another column .
try{
String query=new String(“update customers SET discountprice=price*(100-discount)/100”);
lastname=‘jones’“);DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• Here discount, price and discountprice are the column names
• Discountprice value is calculated using discount and price
Deleting Data from a Table:
Deleting rows is necessary to purge erroneous information from the database and to remove
information that is no longer needed.
Deleting a Row from a Table:
• Row deleted from a table by using the delete from statement.
try{
String query=new String(“delete from customers where lastname=‘jone’ and firstname=‘tom’“);
lastname=‘jones’“);DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Joining Tables

• A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
• Tables are joined in a query using two step process
• First both tables that are being joined must be identified in the FROM clause where tables
are listed one after the other and are separated by a comma
• Next an expression is created in the WHERE clause that identifies the columns that are
used to create the join.
• The joined tables create a logical table that has all the columns of both tables.
• Joining too many tables can cause performance degradation and bring response time to a
crawl.
Example Tables:
try{
String query=new String(“select FirstName,LastName,City,State,Zipcode from
customers,zipcode where zip=zipcode”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
String fn=new String();
String ln=new String();
String street=new String();
String city=new String();
String state=new String();
String zipcode=new String();
String printrow;
fn=rs.getString(1);
Ln=rs.getString(2);
Street=rs.getString(3);
City=rs.getString(4);
State=rs.getString(5);
Zipcode=rs.getString(6);
Printrow=FirstName+” ”+LastName+” ”+city+””+State+””+zipcode;
System.out.println(printrow);}
Parent-Child Join:
• A parent/child join is used to join tables that have a parent/child relationship where rows
in the parent table must exist for rows in the child table to exist
• Only rows that have a matching product number in both tables are placed in the virtual
table that consists of rows from both tables
• Customer cannot order a product that does not exist in the Products table.
• Here product is parent table and order is child table.
try{
String query=new String(“select ordernumber, productname from orders, products where
prodnumber=ProductNumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum
String printrow=new String();
ordernum=rs.getInt(1);
Prodnum=rs.getInt(2);
Printrow=ordernum+” ”+prodnum;
System.out.println(printrow);
}
Multiple Comparison Join:
• WHERE clause expression used to join together tables can be a compound expression
• A compound expression consist of two or more subexpressions each of which evaluated
separately
• A compound expression is used to specify more than one selection criteria used to join
two tables
try{
String query=new String(“select ordernumber, productname ,quantity from orders, products
where prodnumber=ProductNumber and quantity>2”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum,quantity;
String printrow=new String();
ordernum=rs.getInt(1);
Prodnum=rs.getInt(2);
Quantity=rs.getInt(3);
Printrow=ordernum+” ”+prodnum+””+quantity;
System.out.println(printrow);
}
Multitable Join
• More than two tables can be joined together by using the name of each table in he join in
the FROM clause and by defining the join with the appropriate column names in the
WHERE clause expression
• All the tables donot need to have a common value used to join them
try{
String query=new String(“select FirstName,LastName,ordernumber, productname ,quantity
from customers, orders, products where prodnumber=ProductNumber and
custnumber=customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum,quantity;
String printrow=new String();
String fn=new String();
String ln=new String();
String pn=new String();
Fn=rs.getString(1);
Ln=rs.getString(2);
ordernum=rs.getInt(3);
Pn=rs.getString(4);
Quantity=rs.getInt(5);
Printrow=FirstName+””+LastName+””+
ordernum+” ”+prodnum+””+quantity;
System.out.println(printrow);
}
Creating Column Name Qualifier:
• Two tables can have the same column name to store the data element
• Conflicts with the column name can be resolved in a join by using a column name
qualifier.
• A column name qualifier identifies the table that contains the column name
try{
String query=new String(“select
customers.custnumber,Firstname,lastname,ordernumbr,productname,quantity from
customers,orders,products where prodnumber=productnumber and
customers.customernumber, orders.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum,customernum;
String printrow=new String();
String fn=new String();
String ln=new String();
String pn=new String();
Fn=rs.getString(1);
Ln=rs.getString(2);
ordernum=rs.getInt(3);
Pn=rs.getString(4);
Quantity=rs.getInt(5);
Customernum=rs.getInt();
Printrow=fn+””+ln+””+
ordernum+” ”+pn+””+quantity;
System.out.println(printrow);
}
Creating Table Alias:
• A query can be made readable by using table aliases.
• A table alias is an abbreviation for the name of the table and is used in place of the table
name in the join and in the SELECT statement.
• Conditions for making table alias
• With as few letters as possible to save space in the query string
• Representative of the table name, such as the first letter of the table name
• Unique and not a duplicate of another table name, table alias, or column name
try{
String query=new String(“select
c.customernumber,c.firstname,c.lastname,o.ordernumber,p.productname,o.quantity, from
customers c, orders o, products p where o.prodnumber=p.productnumber, and
c.cutomernumber=o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);}
Inner and Outr Join:
• There are two kinds of joins each of which either excludes or includes rows in both tables
of the join that donot match.
• Inner join: an inner join excluldes rows of either table that donot have a matching
value
• Outer join: an outer join includes rows of either table that donot have a matching
value
Inner Join:
• Inner join is used to include only rows of both tables that have matching values
• Unmatched rows are excluded and therefore those rows are not returned in the ResultSet
try{
String query=new String(“select FirstName, LastName,OrderNumber,ProductName,
Quantity from customers,orders,products where
cusomers.custnumber=orders.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Outer Join:- Left, Right, Full
• An outer join occurs when matching and no matching rows of either or both tables are
contained in the join
• There are three kinds of outer joins
1. Left outer join is also known as SQL left join.
• Suppose, we want to join two tables: A and B. Left outer join returns all rows in the left
table (A) and all the matching rows found in the right table (B). It means the result of the
Left join always contains the rows in the left table.
try{
String query=new String(“select FirstName, LastName, OrderNumber from customers
LEFT JOIN orders on customers.custnumber=orders.customernumber”);
o.prodnumber=p.productnumber, and c.cutomernumber=o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
• All rows in the customers is listed.
• In case, there is no matching row in the orders table found for the row in
the customers table, the orderid column in the orders table is populated with NULL
values.
Right Outer JOIN:
• Right outer join returns all rows in the right table and all the matching rows found in the
left table.
• All the rows in the orders table are used in the join regardless if the customer number in
the orders table has a corresponding customer number in the customer table.
• The WHERE clause contains the right outer join operator(=*).
try
{
String query=new String(“select FirstName, LastName, OrderNumber from customers
c,orders o where c.custnumber=* o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);}
Full Outer JOIN
• A full outer join uses all the rows of both tables regardless if they match.
• The full outer join operator(*=*) is a combination of left outer join operator and right
outer join operator.
• We can also use Full JOIN
try
{ String query=new String(“select FirstName, LastName, OrderNumber from customers c,orders
o where c.custnumber*=* o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);

You might also like