Unit-V: JDBC Objects
Unit-V: JDBC Objects
JDBC Objects:
The Concept of JDBC
JDBC Driver Types
JDBC Packages
Overview of the JDBC Process
Database Connection
Statement Objects
Result set
Exceptions
The Concept of
JDBC
A J2ME application supplies database access using the Java Database
Connection (JDBC) interface contained in the JDBC application programming
interface (API)
JDBC interface provides methods to open connection to database and transmit
the message to insert, retrieve, modify, or delete data stored in a database.
The JDBC interface used to to connect to the DBMS, send queries to the
DBMS, and manipulate data returned by the DBMS.
There are many databases available in the market like oracle, DB2 and
Sybase.
Sun micro systems decided to access the database using the high level code
that
The is java.
specifications required a JDBC driver to be a translator that converts low-
level proprietary DBMS messages to low-level messages that are understood
by the JDBC API and vice versa
JDBC driver defines the specifications that describe the functionality of the
JDBC driver and JDBC API contains the methods to connect to the database.
This meant Java programmers could use high-level JDBC interfaces that
are defined in the JDBC API to write a routine that interacts with the
DBMS.
The JDBC interface converts the routine into low-level messages that
conform to the JDBC driver specification and sends them to the JDBC
driver.
The JDBC driver translates the routine into low-level messages that are
understood and processed by the DBMS
JDBC drivers created by DBMS manufacturers have to:
Open a connection between the DBMS and the J2ME application
Translate low-level equivalents of SQL statements sent by the
J2ME application into messages that can be processed by the
DBMS
Return data that conforms to the JDBC specification to the JDBC
driver
Provide transaction management routines that conform to
the JDBC specification
Close the connection between the DBMS and the
J2ME application
JDBC Driver Types
• The JDBC driver specification classifies JDBC drivers into four groups.
• Each group is referred to as a JDBC driver type and addresses a specific need for
communicating with various DBMSs
Type 1 JDBC to ODBC Driver
• Type 1 creates the both JDBC and ODBC(Open data base connectivity) drivers.
• Both ODBC and JDBC have similar driver specifications and an API.
• The JDBC to ODBC driver is used to translate DBMS calls between the JDBC
specification and the ODBC specification.
• The JDBC to ODBC driver receives messages from a J2ME application that
conforms to the JDBC specification
• Those messages are translated by the JDBC to ODBC driver into the ODBC
message format, which is then translated into the message format understood by
the DBMS.
• The extra translation might negatively impact performance.
• This type of driver is recommended only for experimental use or when no other
alternative is available.
Type 2 Java/Native Code Driver
• The Java/Native Code driver uses Java classes to generate platform-specific code
— that is, code only understood by a specific DBMS.
• The manufacturer of the DBMS provides both the Java/Native Code driver and
API classes so the J2ME application can generate the platform-specific code
• Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which
are unique to the database.
• These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge.
• The vendor-specific driver must be installed on each client machine.
• Disadvantage of using a Java/ Native Code driver is the loss of some portability
of code.
• The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3 JDBC Driver
• The Type 3 JDBC driver, also referred to as the Java Protocol.
• The Type 3 JDBC driver converts SQL queries into JDBC-formatted
statements.
• The JDBC-formatted statements are translated into the format required by
the DBMS.
• In a Type 3 driver, a three-tier approach is used to access databases.
• The JDBC clients use standard network sockets to communicate with a
middleware application server.
• The socket information is then translated by the middleware application
server into the call format required by the DBMS, and forwarded to the
database server.
• This kind of driver is extremely flexible, since it requires no code installed
on the client and a single driver can actually provide access to multiple
databases.
• Type 4 JDBC Driver
• The Type 4 JDBC driver is also known as the Type 4 Database Protocol.
• SQL queries do not need to be converted to JDBC-formatted systems. This
is the fastest way to communicate SQL queries to the DBMS.
• In a Type 4 driver, a pure Java-based driver communicates directly with
the vendor's database through socket connection.
• This is the highest performance driver available for the database and is
usually provided by the vendor itself.
• This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
• Ex:MySQL's Connector/J driver is a Type 4 driver.
Which Driver should be Used?
Class.forName("com.mysql.jdbc.Driver");
Create the connection object
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
Create the Statement object
Statement stmt=con.createStatement();
Execute the query
public ResultSet executeQuery(String sql)throws SQLException
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Close the connection object
con.close();
Example
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args)
{
try {
Class.forName(“com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found "+ e);
}
try
{
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/sonoo"
,"root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
catch(SQLException e)
{
System.out.println("SQL exception occured" + e);
}
}
}
Result
The above code sample will produce the following result. The result may
vary.
id name job
1 alok trainee
2 ravi trainee
Statement Objects
• 3 types of Statement objects is used to execute the query.
• These objects are
• Statement, which executes a query immediately;
• PreparedStatement, which is used to execute a compiled query
• CallableStatement, which is used to execute store procedures.
Statement
The executeQuery() which is passed the query as an argument.
It returns one ResultSet object that contains rows, columns, and metadata that
represent data requested by the query.
The execute() method of the Statement object is used when multiple results may
be returned.
The executeUpdate() is used to execute queries that contain INSERT,
UPDATE, DELETE, and DDL statements.,which change values in a row and
remove a row, respectively
The createStatement() method of the Connection object is called to return a
Ex: executeQuery
Statement object executeUpdate
String query = "SELECT * FROM SET PAID='Y' WHERE BALANCE
Customers"; = '0';
DataRequest = DataRequest = Db.createStatement();
Db.createStatement(); rowsUpdated =
Results = DataRequest.executeQuery DataRequest.executeUpdate (query);
(query);
String query = "UPDATE
Customers
PreparedStatement
An SQL query can be precompiled and executed by using the
PreparedStatement object.
A question mark is used as a placeholder for a value that is inserted into the
query after the query is compiled. It is this value that changes each time the
query is executed.
The preparedStatement() method of the Connection object is called to return
the PreparedStatement object.
The preparedStatement() method is passed the query that is then
precompiled.
The setXXX() method of the PreparedStatement object is used to replace the
question mark with the value passed to the setXXX() method.
There are a number of setXXX() methods available in the PreparedStatement
object, each of which specifies the data type of the value that is being passed
to the setXXX()
The setXXX() requires two parameters. The first parameter is an integer that
identifies the position of the question mark placeholder, and the second
parameter is the value that replaces the question mark placeholder.
CallableStatement
The CallableStatement is used to call a stored procedure from within a J2ME
object. A stored procedure is a block of code and is identified by a unique name
The stored procedure is executed by invoking the name of the stored
procedure.
The CallableStatement object uses three types of parameters
The IN parameter contains any data that needs to be passed to the stored procedure
and whose value is assigned using the setXXX() method
The OUT parameter contains the value returned by the stored procedures, if any.
The OUT parameter must be registered using the registerOutParameter() method and
then is later retrieved by the J2ME application using the getXXX() method.
The INOUT parameter is a single parameter used for both passing information to
the stored procedure and retrieving information from a stored procedure
The registerOutParameter() method requires two parameters
1. integer that represents the number of the parameter of the stored procedure
The execute() of the CallableStatement object is called next to execute the query.
After the stored procedure is executed, the getString() method is called to return
the value of the specified parameter of the stored procedure
Ex:
String query = "{ CALL LastOrderNumber (?)}";
CallableStatement cstatement = Db.prepareCall(query);
cstatement.registerOutParameter(1, Types. VARCHAR);
cstatement.execute();
lastOrderNumber = cstatement.getString(1);
ResultSet
A query is used to update, delete, and retrieve information stored in a database.
The executeQuery() method is used to send the query to the DBMS for processing
and returns a ResultSet object that contains data requested by the query.
The ResultSet object contains methods that are used to copy data to a Java collection
of objects or variable(s) for further processing.
Data in a ResultSet object is logically organized into a virtual table consisting of
rows and columns. In addition to data, the ResultSet object also contains
metadata, such as column names, column size, and column data type.
The ResultSet uses a virtual cursor to point to a row of the virtual table.
A J2ME application must move the virtual cursor to each row, then use other
methods of the ResultSet object to interact with the data stored in columns of that row.
The virtual cursor is positioned above the first row of data when the ResultSet is
returned by the executeQuery() method. This means that the virtual cursor must be
moved to the first row using the next() method. The next() method returns a boolean
Once the virtual cursor points to a row, the getXXX() method is used to copy data from the
Db.createStatement();
Results = DataRequest.executeQuery (query);
boolean Records = Results.next();
do {
FirstName = Results.getString ( 1 ) ;
LastName = Results.getString ( 2 ) ;
printrow = FirstName + " " + LastName;
System.out.println(printrow);
} while (Results.next() );
Scrollable ResultSet
Six methods of the ResultSet object are used to position the virtual cursor, in addition to the
next() method .These are first(), last(), previous(), absolute(), relative(), and getRow().
The Statement object that is created using the createStatement() of the Connection object must
be set up to handle a scrollable ResultSet by passing the createStatement() method one of three
constants.
These constants are TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE,
and TYPE_SCROLL_SENSITIVE
Not All JDBC Drivers Are Scrollable
Ex:
DataRequest = Db.createStatement(TYPE_SCROLL_INSENSITIVE);
Results = DataRequest.executeQuery (query);
do
{ Results.first();
Results.last();
Results.previous();
Results.absolute(10);
Results.relative(-2);
Results.relative(2);
FirstName = Results.getString ( 1 ) ;
LastName = Results.getString ( 2 ) ;
printrow = FirstName + " " + LastName;
System.out.println(printrow);
} while (Results.next() );
Specify Number of Rows to Return
The fetch size is set by using the setFetchSize() method
DataRequest.setFetchSize(500);
Updatable ResultSet
Rows contained in the ResultSet can be updated similar to how rows in a
table can be updated.
This is made possible by passing the createStatement() method of
the
Connection object the CONCUR_UPDATABLE. Alternatively, the
CONCUR_READ_ONLY constant can be passed to the createStatement()
method to prevent the ResultSet from being updated.
There are three ways to update a ResultSet. These are updating values in a
row, deleting a row, and inserting a new row.
updateXXX() method is used to change the value of a column in the current
row of the ResultSet.
Ex:
DataRequest = Db.createStatement(ResultSet.CONCUR_UPDATABLE);
Results = DataRequest.executeQuery (query);
Results.updateString ("LastName", "Smith");
Results.updateRow();
Delete a Row in the
ResultSet
The deleteRow() method is used to remove
a row from a ResultSet.
The deleteRow() method is passed an integer that contains the number of the
row to be deleted.
The deleteRow() method is then passed a zero integer indicating that the
current row must be deleted
Ex:Results.deleteRow(0);
Insert a Row in the ResultSet
Inserting a row into the ResultSet is accomplished using basically the same
technique used to update the ResultSet.
The updateRow() method is called after all the updateXXX() methods are
called.
The updateRow() method changes values in columns of the current row of the
ResultSet based on the values of the updateXXX() methods
Ex:
String query = "SELECT FirstName,LastName FROM Customers";
DataRequest = Db.createStatement(CONCUR_UPDATABLE);
Results = DataRequest.executeQuery (query);
Results.updateString (1, "Tom");
Results.updateString (2, "Smith"); Results.insertRow();
Transaction Processing
A database transaction consists of a set of SQL statements, each of which must be
successfully completed for the transaction to be completed.
If one fails, SQL statements that executed successfully up to that point in the
transaction must be rolled back.
A database transaction isn’t completed until the J2ME application calls the
commit() method of the Connection object.
All SQL statements executed before the call to the commit() method can be rolled
back. However, once the commit() method is called, none of the SQL statements can
be rolled back.
The commit() method was automatically called because the DBMS has an
AutoCommit feature that is by default set to true.
The AutoCommit feature must be deactivated by calling the setAutoCommit()
method and passing it a false parameter.
Ex:
Database .setAutoCommit(false) ;
String query1 = "UPDATE Customers SET Street = '5 Main Street' " "WHERE
FirstName = 'Bob'
Savepoints
The J2ME application can control the number of tasks that are rolled back by
using savepoints.
A savepoint is a virtual marker that defines the task at which the rollback
stops
A savepoint is created after the execution of the first UPDATE SQL
statement
There can be many savepoints in a transaction; each is identified by a unique
name. The savepoint name is then passed to the rollback() method to specify the
point within the transaction where the rollback is to stop.
The releaseSavepoint() method is called to remove the savepoint from the
transaction
Savepoint s1 = Database.setSavepoint ("sp1");
Database.releaseSavepoint ("sp1");
Batch Statements
Whenever the commit() method is called, all ResultSet objects that were created
for the transaction are closed.
Sometimes a J2ME application needs to keep the ResultSet open even after
the commit() method is called.
We can control whether or not ResultSet objects are closed following the call to
the commit() method (called “holdability”) by passing one of two constants to the
createStatement() method.
These constants are HOLD_CURSORS_OVER_COMMIT and
CLOSE_CURSORS_AT_COMMIT.
ResultSet Metadata
Two types of metadata can be retrieved from the DBMS: metadata that
describes the database and metadata that describes the ResultSet.
Metadata that describes the ResultSet is retrieved by calling the
getMetaData() method of the ResultSet object. This returns a ResultSetMetaData
object
ResultSetMetaData rm = Result.getMetaData()
Tables
Indexing
Inserting Data into Tables
Selecting Data from a Table
Metadata
Updating Tables
Deleting form a Table.
Joining Tables
Calculating Data
Grouping and Ordering Data
Sub queries
JDBC and Embedded SQL:
The Model A program style is used to execute SQL requests that use the
execute() or executeUpdate() methods and don’t return a ResultSet.
The Model B program style is used to execute SQL requests that use the
executeQuery() method, which returns a ResultSet.
A model J2ME application that doesn’t retrieve catch (SQLException error) {
Information from a database (Model A) System.err.println("Cannot connect to the
database. "+ error); if(Database != null) {
import java.sql.*; try { Database.close(); }
public class ModelA { catch(SQLException er){} }
private Connection Database; private Statement System.exit(2); }
DataRequest; public ModelA () try { // insert example code here }
{ catch ( SQLException error )
String url = "jdbc:odbc:CustomerInformation"; { System.err.println("SQL error."
String userID = "jim"; + error);
if(Database != null) {
String password = "keogh";
try { Database.close(); }
try {
catch(SQLException er){}
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
}
Database =
DriverManager.getConnection(url,userID,pass System.exit(3);
word); }
} if(Database != null) { try { Database.close(); }
catch (ClassNotFoundException error) { catch(SQLException er){}
System.err.println("Unable to load the }}
JDBC/ODBC bridge." + error); public static void main ( String args [] )
System.exit(1); } {
final ModelA sql1 = new ModelA ();
System.exit ( 0 ) ;
The Model B program is similar to the Model A program in that the constructor definition
The second try {} block in Model B is where you place the try {} block contained how to
retrieve information from a database. This try {} executes a query and returns a ResultSet
object called Results
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
DownRow() retrieves data stored in columns of the ResultSet and assigns those values to
variables.
After DownRow() extracts data from the current row of the ResultSet, control returns to
DisplayResults(), where the next() method is called and the results are evaluated by the
while.
If the next() method returns a true value, then DownRow() is recalled, otherwise
the do…while loop is exited and control returns to the constructor.
import java.sql.*; public class ModelB catch(SQLException er){} }
{ private Connection Database; private Statement System.exit(3); }
DataRequest; private ResultSet Results; public if(Database != null) {
ModelB () {
try { Database.close(); }
String url = "jdbc:odbc:CustomerInformation";
catch(SQLException er){}} }
String userID = "jim";
private void DisplayResults (ResultSet DisplayResults)
String password = "keogh"; try { throws SQLException {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver"); boolean Records = DisplayResults.next();
Database = if (!Records ) {
DriverManager.getConnection(url,userID,pass
word); } System.out.println( "No data returned"); return; }
try { do { DownRow( DisplayResults) ;
catch (ClassNotFoundException error) {
} while ( DisplayResults.next() ); }
System.err.println("Unable to load the
JDBC/ODBC bridge." + error); catch (SQLException error ) { System.err.println("Data
System.exit(1); } display error." + error); if(Database != null) {
catch (SQLException error) { try { Database.close(); } catch(SQLException er){}}
System.err.println("Cannot connect to the System.exit(4); }}
database." + error); System.exit(2); } private void DownRow ( ResultSet DisplayResults )
try{ // Enter example code here } throws SQLException {
catch ( SQLException error ) //Enter new DownRow() code here}
{ System.err.println("SQL error." public static void main ( String args [] ) {
+ error); final ModelB sql1 = new ModelB ();
if(Database != null) { System.exit(0);
try { Database.close(); } }}
Tables
Create a Table , Requiring Data in a Column , Setting a Default Value for a Column ,
Create a Table
The query contains the CREATE TABLE SQL statement that contains the name of
the table.
Following the table name are the column definitions, which are enclosed in
parentheses
The data type of the column and the column size follow the column name
All the SQL commands are enclosed in double quotation marks and assigned to a
String object called query.
Next, the program creates an 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.
The query is sent to the DBMS using the executeQuery() method.
Example
try {
String query = "CREATE TABLE CustomerAddress (" + " CustomerNumber
CHAR(30), " + " CustomerStreet CHAR(30), " + " CustomerCity CHAR(30), "
+ " CustomerZip CHAR(30))";
DataRequest = Database.createStatement();
DataRequest.execute(query);
DataRequest.close();
}
Requiring Data in a Column
There are business rules that require a value in specific columns of a row, such as
the columns that contain a customer’s name.
We can require the DBMS to reject rows that are missing a value in specific
columns by using the NOT NULL clause in the query when the table is created.
Ex: How the NOT NULL clause is used in a query.
try
{ Stri query="CREATE TABLE CustomerAddress ( " + "CustomerNumber
ng
CHAR(30) NULL," + "CustomerStreet CHAR(30) NULL," +
NOT
"CustomerCity CHAR(30) NOT NULL," + "CustomerZip
NOT CHAR(30)
NOT NULL)";
DataRequest=Database.createStatement();
DataRequest.execute (query );
DataRequest.close();
}
Setting a Default Value for a Column
The DBMS can enter a default value into a column automatically if the column is
left empty whenever a new row is inserted into the table.
Any value can be used as the default value as long as the value conforms to the
data type and size of the column.
A default value is assigned to a column when you create the table by using the
DEFAULT clause.
The DEFAULT clause is followed in the query by the value that the DBMS will
place in the column if the column is empty in the incoming row.
Ex:
try {
String query = "CREATE TABLE CustomerAddress ( " + "CustomerNumber
CHAR(30) NOT NULL," + "CustomerStreet CHAR(30) NOT NULL," +
"CustomerCity CHAR(30) NOT NULL," +
"CustomerZip CHAR(30) NOT NULL DEFAULT '07660')";
DataRequest = Database.createStatement(); DataRequest.executeUpdate (query );
Drop a Table
Ex:
try {
String query = new String ("DROP TABLE CustomerAddress");
DataRequest = Database.createStatement();
DataRequest. execute(query); DataRequest.close();
}
Indexing
Create an Index, Designating a Primary Key, Creating a Secondary Index ,
Creating a Clustered Index , Drop an Index
Indexes are special lookup tables that the database search engine can
use to speed up data retrieval. Simply, an index is a pointer to data in a
table.
An index in a database is very similar to an index in the back of a
book.
An index helps to speed up SELECT queries and WHERE clauses, but it
slows down data input, with the UPDATE and the INSERT statements.
Indexes can be created or dropped with no effect on the data
Indexes can also be unique, like the UNIQUE constraint, in that the index
prevents duplicate entries in the column or combination of columns on
which there is an index.
Create an Index
The CREATE INDEX statement contains the name of the index and any
Ex:Creating a unique index
try {
String query = "CREATE UNIQUE INDEX CustNum " + "ON
CustomerAddress (CustomerNumber)";
DataRequest = Database.createStatement();
DataRequest.execute (query);
DataRequest.close();
}
Designating a Primary Key
try {
String query = "Create Table Orders ( " + "OrderNumber CHAR(30) NOT
NULL, " + "CustomerNumber CHAR(30), " + "ProductNumber CHAR(30),
" + "CONSTRAINT ORDERS_PK PRIMARY KEY (OrderNumber))";
DataRequest = Database.createStatement();
DataRequest. execute(query);
DataRequest.close();
}
Creating a Secondary Index
try {
String query = new String ("CREATE INDEX CustZip " + "ON
CustomerAddress (CustomerZip) ");
DataRequest = Database.createStatement(); DataRequest. execute(query);
DataRequest.close();
}
Creating a Clustered Index
A clustered index is an index whose key is created from two or more
columns of a table,
The order in which column names appear in the ON clause plays a
critical role in the index.
Ex: Creating a clustered index
try {
String query = "CREATE INDEX CustName " + " ON Customers
(LastName, FirstName)";
DataRequest = Database.createStatement();
DataRequest.execute (query);
DataRequest.close();
Drop an Index
An existing index can be removed from the database by using the DROP
INDEX statement, which is similar in construction to the DROP TABLE
statement
try {
String query = new String("DROP INDEX CustName ON Customers ");
DataRequest = Database.createStatement();
DataRequest. execute(query); DataRequest.close();
}
Inserting Data into Tables
Insert a Row , Insert the System Date into a Column , Insert the System
Time into a Column , Insert a Timestamp into a Column
The INSERT INTO statement is used to insert a new row into a table.
The INSERT INTO statement contains the name of the table into which the
row is to be inserted and the name of the columns in which values are
inserted.
The VALUES clause is used to define the values to be placed into the row.
Each value is placed in the VALUES clause in the same order as the
corresponding column’s name.
try {
String query = new String (
"INSERT INTO Customers (CustomerNumber ,FirstName, "+ " LastName,
DateOfFirstOrder )" + " VALUES ( 4,'Mary','Jones', CURRENT_DATE)");
DataRequest = Database.createStatement();
DataRequest.executeUpdate (query );
DataRequest.close();
Insert the System Time into a Column
Call the CURRENT_TIME() function whenever a column requires the
current time.
The CURRENT_TIME() function is called by the DBMS when the query is
processed, and it returns the current time of the server
try {
String query = new String (
"INSERT INTO Customers (CustomerNumber ,FirstName, "+ " LastName,
TimeOfFirstOrder ) " +
" VALUES ( 2,'Bob','Jones', CURRENT_TIME() )") ;
DataRequest = Database.createStatement();
DataRequest.executeUpdate(query ); DataRequest.close();
}
Insert a Timestamp into a Column
A timestamp consists 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 the timestamp into a column by calling the TIMESTAMP()
function
Ex: Inserting timestamp a column
try {
String query = new String (
"INSERT INTO Customers (CustomerNumber ,FirstName, "+ " LastName,
FirstOrder ) " +
" VALUES ( 2,'Bob','Jones', CURRENT_TIMESTAMP()) )";
}
Request Rows and Columns
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 Clauses
The WHERE clause in a SELECT statement can evaluate values in
more than one column of a row by using the AND, OR, and NOT
clauses to combine expressions.
The AND clause requires that both expressions in the compound
expression evaluate to true before the WHERE clause expression
evaluates true and includes a specified row in the ResultSet.
The OR clause requires that at least one of the expressions in the
compound expression evaluate to true before the WHERE clause
expression evaluates true.
And the NOT clause is used to reverse the logic, changing an
expression that evaluates true to a false. }
AND Clause
The purpose of the AND clause is to join two subexpressions together
to form one compound expression.
The 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, the current row being
evaluated by the DBMS is returned to our program.
The equal and not equal operators are used to determine whether the
value in the WHERE clause expression is or isn’t in the specified
column.
Not Equal Operator
The not equal operator is used in a WHERE clause expression or sub
expression to identify rows that should not be returned by the DBMS.
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.
Name of Column
private void DownRow ( ResultSet DisplayResults ) throws
SQLException {
ResultSetMetaData metadata = DisplayResults.getMetaData (); String
ColumnName = new String();
String printrow;
ColumnName = metadata.getColumnLabel (9) ;
System.out.println("Column Name: " + ColumnName);
}
Column Size
Unmatched rows are excluded, and therefore those rows are not returned in
the ResultSet
Outer Join—Left, Right, Full
An outer join occurs when matching and nonmatching rows of either or both
tables are contained in the join. There are three kinds of outer joins:
Left outer join :All matched and unmatched rows of the first table and
matched rows of the second table are included in the join.
Right outer join: Matched rows of the first table and matched and
unmatched rows of the second table are included in the join.
Full outer join: Matched and unmatched rows of both tables are included in
the join.
Left Outer Join
String query = new String ( " SELECT FirstName, LastName,OrderNumber "
+ " FROM Customers LEFT JOIN Orders " + " ON Customers.CustNumber =
Orders.CustomerNumber");
Right outer join
String query = new String ( " SELECT FirstName, LastName,OrderNumber" + "
FROM Customers c, Orders o" + " WHERE c.CustNumber =*
o.CustomerNumber");
Full outer join:
String query = new String( " SELECT FirstName, LastName,OrderNumber " + "
Calculating Data
The DBMS can calculate values in a table and return the result of the
calculation in the ResultSet by using one of the five built-in calculation
functions:
■ SUM() tallies values in a column passed to the built-in function.
■ AVG() averages values in a column passed to the built-in function.
■MIN() determines the minimum value in a column passed to the built-in
function.
■MAX() determines the maximum value in a column passed to the built-in
function.
■COUNT() determines the number of rows in a column passed to the built-in
function.
Determining the maximum value in
Determining the sum of values in
a column
a column
String query = new String ("SELECT
String query = new String
COUNT(Quantity) " + "FROM Orders ");
("SELECT SUM(Quantity) " +
"FROM Orders "); Count All Rows in a Table
Determining the average of String query = new String ("SELECT
values in a column COUNT(*) " + "FROM Orders ");
String query = new String Retrieve Multiple Counts
("SELECT AVG(Quantity) " + String query = new String ("SELECT
"FROM Orders "); COUNT(*), COUNT(Quantity) " +
DataRequest = Database. "FROM Orders ");
Determining the minimum Calculate a Subset of Rows
value in a column String query = new String (
String query = new String ("SELECT " SELECT COUNT(OrderNumber),
Calculate Without
MIN(Quantity) Using
" + "FROM Built-in
Orders "); FROM Orders o,SUM(Quantity)
AVG(Quantity), customers c " "++
Functions " WHERE o.CustomerNumber =
"String query = new String ( c.CustNumber");
" SELECT StoreNumber, Sales -
Estimate " + " FROM Sales ");
Grouping and Ordering Data
The order in which rows appear in the ResultSet can be grouped into similar
values or sorted in ascending or descending order by using the GROUP BY
clause or the ORDER BY clause
GROUP BY
A complex sort is when multiple columns are used for the sort, such as
Grouping the ResultSet
String query = new String (" SELECT StoreNumber, SUM(Sales) " + "
FROM Sales " + " Group By StoreNumber");
The HAVING clause sets the criteria for a row to be included in a group.
Here are the requirements for using a conditional expression in the HAVING
clause:
■ The expression must result in a single value.
■ The result must appear in every column named in the expression.
Conditional grouping in the ResultSet
String query = new String ("SELECT StoreNumber, SUM(Sales) " + " FROM
Sales " + " Group By StoreNumber" + " HAVING SUM(Sales) > 400");