0% found this document useful (0 votes)
165 views107 pages

Unit-V: JDBC Objects

The document discusses JDBC objects and concepts. It describes the different types of JDBC drivers (Type 1 to Type 4), the JDBC packages and interfaces, and the basic JDBC process which involves connecting to a database, executing statements and queries, processing result sets, and closing connections. It also discusses statement objects like Statement, PreparedStatement and CallableStatement and their uses in executing queries and stored procedures.

Uploaded by

M.Thenmozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views107 pages

Unit-V: JDBC Objects

The document discusses JDBC objects and concepts. It describes the different types of JDBC drivers (Type 1 to Type 4), the JDBC packages and interfaces, and the basic JDBC process which involves connecting to a database, executing statements and queries, processing result sets, and closing connections. It also discusses statement objects like Statement, PreparedStatement and CallableStatement and their uses in executing queries and stored procedures.

Uploaded by

M.Thenmozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 107

Unit-V

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?

• If you are accessing one type of database, such as Oracle, Sybase,


or IBM, the preferred driver type is 4.
• If your Java application is accessing multiple types of databases at
the same time, type 3 is the preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4
driver is not available yet for your database.
• The type 1 driver is not considered a deployment-level driver, and is
typically used for development and testing purposes only.
• JDBC packages
- JDBC API is contained in two packages.
1.java.sql contains core JDBC interfaces that provide the basics
for connecting to the DBMS and interacting with data stored in the
DBMS. java.sql is part of the J2SE.
2.javax.sql, is the JDBC interface that interacts with Java Naming and
Directory Interface (JNDI) and manages connection pooling, among
other advanced JDBC features.
• Overview of the JDBC Process
• The process of interacting the Java application with DBMS is
divided into 5 routines.
1. loading the JDBC driver,
2. connecting to the DBMS,
3. creating and executing a statement
4. processed data returned by the DBMS
5. terminating the connection with the DBMS.
Register the driver class

Register the driver class


The forName() method of Class class is used to register the
driver class.
This method is used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNo
tFoundException  
Example to register the OracleDriver class

Class.forName("com.mysql.jdbc.Driver");  
Create the connection object

The getConnection() method of DriverManager class is used to establish


connection with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException  
2) public static Connection getConnection(String url,String name,String password)  
throws SQLException  

Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection(  
"jdbc:mysql://localhost:3306/sonoo","root","root");  
Create the Statement object

The createStatement() method of Connection interface is used


to create statement.
The object of statement is responsible to execute queries with
the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
  
Example to create the statement object

Statement stmt=con.createStatement();  
Execute the query

The executeQuery() method of Statement interface is used to execute


queries to the database.
This method returns the object of ResultSet that can be used to get all the
records of a table.
Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");  
  
while(rs.next()){  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  
}  
Close the connection object

By closing connection object statement and ResultSet will be


closed automatically.
The close() method of Connection interface is used to close the
connection.
Syntax of close() method
public void close()throws SQLException  

Example to close connection

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");

System.out.println("id name job");

while (rs.next()) { int id = rs.getInt("id");


String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job); } }

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

 These parameters are IN, OUT, and INOUT.

 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

 2. the data type of the value returned by 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

row to a collection, object, or variable.

 Reading the ResultSet

Ex:String query = "SELECT FirstName,LastName FROM Customers"; DataRequest =

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

 Another way to combine SQL statements into a transaction is to batch statements


together into a single transaction and then execute the entire transaction.
 Adding batch can be done By using the addBatch() method of the Statement
object.
 The addBatch() method receives an SQL statement as a parameter and places the
SQL statement in the batch.
 Once all the SQL statements that make up the transaction are included in the batch,
the executeBatch() method is called to execute the entire batch at the same time.
 The executeBatch() method returns an int array that contains the number of
SQL statements executed successfully.
 The int array is displayed if a BatchUpdateException error is thrown during the
execution of the batch.
 The batch can be cleared of SQL statements by using the clearBatch() method.

 The transaction must be committed using the commit() method.


Ex:
Database .setAutoCommit(false)
String query1 = "UPDATE Customers SET Street = '5 Main
Street' " + "WHERE FirstName = 'Bob'";
String query2 = "UPDATE Customers SET Street = '10 Main
Street' " + "WHERE FirstName = 'Tim'";
DataRequest= Database.createStatement();
DataRequest.addBatch(query1);
DataRequest.addBatch(query2);
int [ ] updated = DataRequest.executeBatch ();
Database.commit();
DataRequest.clearBatch();
}
 Keeping ResultSet Objects Open

 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.

 Auto generated Keys

 It is common for a DBMS to automatically generate unique keys for a table as


rows are inserted into the table.
 The getGeneratedKeys() method of the Statement object is called to return keys
 Metadata
 Metadata is data about data

 A J2ME application can access metadata by using the DatabaseMetaData


interface.
 The DatabaseMetaData interface is used to retrieve information about
databases, tables, columns, and indexes, among other information about the
DBMS.
 A J2ME application retrieves metadata about the database by calling the
getMetaData() method of the Connection object.
 The getMetaData() method returns a DatabaseMetaData object that contains
information about the database and its components.
 Here are some of the more commonly used DatabaseMetaData object
methods:

getDatabaseProductName() Returns the product name of the database

getUserName() Returns the user name


 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()

 The more commonly called methods are

getColumnCount() Returns the number of columns contained in the ResultSet

getColumnName(int number) Returns the name of the column specified by the


column number
getColumnType(int number) Returns the data type of the column specified by
 Data Types
 The setXXX() and getXXX() methods are used to set a value of a specific data
type and to retrieve a value of a specific data type. The XXX in the name of these
methods is replaced with the name of the data type.
Exceptions

 Three kinds of exceptions are thrown by JDBC methods.


 These are SQLException, SQLWarning, and DataTruncation.
SQLException commonly reflects an SQL syntax error in the query and is
thrown by many of the methods contained in the java.sql package.
 The getNextException() method of the SQLException object is used to return
details about the SQL error or a null if the last exception was retrieved. The
getErrorCode() method of the SQLException object is used to retrieve vendor-
specific error codes
 The getWarnings() method of the Connection object retrieves the warning, and
the getNextWarning() method of the Connection object retrieves subsequent
warnings.
JDBC and Embedded SQL:
Model Program

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:

 Two programming styles—referred to as Model A and Model B—are used in a


J2ME application can interact with a DBMS.

 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

 Model B also 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

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

 A developer may have the right to remove a table

 In addition to losing data elements stored in the table, dropping a table


may affect the integrity of the database and tables that relate to values in
the dropped table.
 Using the Drop Table statement in the query drops 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

 An index is created by using the CREATE INDEX statement in a query

 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

A secondary index is created by using the CREATE INDEX statement in a


query without the use of the UNIQUE modifier. This means that a secondary
index can have duplicate values.

Ex: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

Ex: Dropping an index

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 executeUpdate() method is used to execute a query that inserts a


row, among other tasks.

 The executeUpdate() method does not return a ResultSet, therefore we


should use the Model A program
Insert a Row

 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.

Ex: Inserting a row into a table


try {
String query = "INSERT INTO
Customers " +
" (CustomerNumber, FirstName, LastName, DateOfFirstOrder) " + " VALUES
(1,'Mary','Smith','10/10/2001') ";
DataRequest = Database.createStatement(); DataRequest.executeUpdate
(query); DataRequest.close();
Insert the System Date into a Column
Sometimes business rules require that the current date be placed into a
column of a new row.
 We can place the system date into a column by calling the
CURRENT_DATE function. This is not implemented in all versions of
DBMSs
Microsoft Access uses NOW. Oracle uses SYSDATE, and DB2 uses
CURRENT DATE .

 Ex: Inserting the system date into a column

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

 Ex: Inserting current time a column

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()) )";

DataRequest = Database.createStatement(); DataRequest.executeUpdate


(query ); DataRequest.close();
}
Selecting Data from a Table
1.Select All Data from a Table
2.Request One Column
3.Request Multiple Columns
4.Request Rows
5.Request Rows and Columns
6.AND, OR, and NOT
Clauses
7.Join Multiple Compound Expressions
8.Equal and Not Equal Operators
9. Less Than and Greater Than
Operators
10.Less Than or Equal to and Greater Than or Equal To
11.Between Operator
12.LIKE Operator
13.ISNULL Operator
14.DISTINCT Modifier
15.IN Modifier
16.NOT IN Modifier
1. Select All Data from a Table
The SELECT statement is used to retrieve data from a table
 The executeQuery() method, which is used to execute the query, returns
a ResultSet object.
 Ex:
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();
}
Copying values from the ResultSet
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.getString
( 3 ) ; City = DisplayResults.getString ( 4 ) ;
State = DisplayResults.getString ( 5 ) ; ZipCode =
DisplayResults.getString ( 6 ) ;
printrow = FirstName + " " + LastName + " " + City + " " + State + " "
+ ZipCode;
System.out.println(printrow);
Request One Column
try {
String query = new String ("SELECT LastName FROM Customers");
DataRequest = Database.createStatement();
Results = DataRequest.executeQuery (query);
DisplayResults (Results); DataRequest.close();
}

Copying values from the ResultSet

private void DownRow ( ResultSet DisplayResults )throws


SQLException
{
String LastName= new String();
LastName = DisplayResults.getString ( 1 ) ;
System.out.println(LastName);
}
Request Rows
try {
String query = new String ("SELECT " +
"FirstName, LastName, Street, City, State, ZipCode " + " FROM
Customers " +
"WHERE LastName = 'Jones' "); DataRequest =
Database.createStatement(); Results = DataRequest.executeQuery
(query); DisplayResults (Results); DataRequest.close();

}
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.

Using the AND clause to form a compound expression in the WHERE


clause
try {
String query = new String ("SELECT FirstName, LastName " + " FROM
Customers " +
" WHERE LastName = 'Jones' " + " AND FirstName = 'Bob'");
DataRequest = Database.createStatement(); Results =
DataRequest.executeQuery (query); DisplayResults (Results);
DataRequest.close();
}
OR Clause
 The OR clause is used to create a compound expression using two
subexpressions in the same way as the AND clause.
 However, the OR clause tells the DBMS that the compound
expression evaluates to a boolean true if either of the two
subexpressions evaluates to a boolean true. .

Using the OR clause to form a compound expression in the WHERE


clause
try {
String query = new String ("SELECT FirstName, LastName " + " FROM
Customers " +
" WHERE FirstName = 'Mary' " + " OR FirstName = 'Bob'");
DataRequest = Database.createStatement(); Results =
DataRequest.executeQuery (query); DisplayResults (Results);
DataRequest.close();
}
NOT Clause
 The NOT clause reverses the logic of the subexpression contained in
the WHERE NOT clause.
 If the subexpression evaluates to a boolean true, the NOT clause
reverses the logic to return a boolean false.
 In contrast, if the subexpression evaluates to a boolean false, the
compound expression evaluates to a boolean true. .

Using the NOT clause to form a compound expression in the WHERE


clause
try {
String query = new String( "SELECT FirstName, LastName " + "FROM
Customers " +
"WHERE NOT FirstName = 'Mary' " ); DataRequest =
Database.createStatement(); Results = DataRequest.executeQuery
(query); DisplayResults (Results); DataRequest.close();
}
Join Multiple Compound Expressions
 The AND and OR clauses are used to link together two or more
subexpressions, which results in a compound expression.
 There can be multiple compound expressions within a WHERE clause
expression.
 A word of caution: the AND clause has a higher precedence than the
OR clause, so the OR clause must be placed within parentheses
 Example:

WHERE FirstName = 'Bob' AND LastName = 'Smith AND ( Dept = '42'


OR Dept = '45')
Equal and Not Equal Operators

 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.

Excluding rows from the ResultSet using the not equal

operator String query = new String ("SELECT " +


"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers " +
"WHERE NOT Sales = 50000 " );
Less Than and Greater Than Operators
 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

Less Than or Equal to, Greater Than or


Equal To
 A drawback of using the less than and greater than operators is that
rows containing the value of the WHERE clause expression are not
returned in the ResultSet.
 Alternatively, the less than or equal to and the greater than or equal
to operators can be used to include rows that contain the WHERE
clause expression.
 Ex:
String query = new String ("SELECT " +
"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers " +
"WHERE Sales <= 50000 " );
Between Operator
 The BETWEEN operator is used to define a range of values to be
used as the value of the selection expression.
 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 the
range
 All values in the range, including the first and last values, are
considered when the DBMS evaluates the value of the column specified
in the selection expression.

Using the BETWEEN operator in the WHERE clause expression

String query = new String("SELECT " +


"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers " +
"WHERE Sales BETWEEN 20000 AND 39999 " );
LIKE Operator
 The 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 is an exact
match and a wildcard character that is used to match any other character.
 Here are the wildcards that are used with the LIKE operator:
Underscore (_) A single-character wildcard character. For example, if
you are unsure whether the customer’s last name is Anderson or
Andersen, use the underscore in place of the character that is in question,
as in Anders_n.
Percent (%) A multicharacter wildcard character used to match any
number of characters. For example, Smi% is used to match a value of a
column where the first three characters are Smi followed by any other
character(s).
Ex: String query = new String ("SELECT " +
"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers " +
"WHERE LastName LIKE 'Smi%' ");
ISNULL Operator
 The IS NULL operator is used to determine whether a specified
column does not contain any value.
 Note that the number zero or a space are not NULL values.

 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.

Using the IS NULL operator in the WHERE clause expression


String query = new String ("SELECT " +
"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers " +
"WHERE State IS NULL ");
DISTINCT Modifier
ResultSet includes duplicate rows unless a primary index is created for
the table or only unique rows are required in the table
 If you want to exclude all but one copy of a row from the ResultSet.

 You can do this by using the DISTINCT modifier in the SELECT


statement
Using the DISTINCT modifier

String query = new String ("SELECT DISTINCT " +


"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers ");
IN Modifier
 The 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

Using the IN modifier in the WHERE clause

String query = new String ("SELECT " +


"FirstName, LastName, Street, City, State, ZipCode, Sales " + " FROM
Customers " +
" WHERE Sales IN (20000, 30000, 40000) " );
NOT IN Modifier
 The NOT IN modifier is similar to the IN modifier, except the NOT IN
modifier reverses the logic. That is, it identifies a set of values that
shouldn’t match rows returned to the program.

Using the IN modifier in the WHERE clause

String query = new String ("SELECT " +


"FirstName, LastName, Street, City, State, ZipCode, Sales " + " FROM
Customers " +
" WHERE Sales NOT IN (20000, 30000, 40000) " );
Metadata
Metadata is data that describes data

Metadata is returned with the ResultSet object and can be extracted


from the ResultSet object by creating a ResultSetMetaData.
The most commonly used metadata are
■ Column name
■ Column number
■ Column data type
■ Column width
Number of Columns in ResultSet
private void DownRow ( ResultSet DisplayResults )throws
SQLException
{
ResultSetMetaData metadata = DisplayResults.getMetaData (); int
NumberOfColumns;
String printrow;
NumberOfColumns = metadata.getColumnCount ();
System.out.println("Number Of Columns: " + NumberOfColumns);
}
Data Type of Column
private void DownRow ( ResultSet DisplayResults ) throws
SQLException
{
ResultSetMetaData metadata = DisplayResults.getMetaData (); String
ColumnType = new String();
String printrow;
ColumnType = metadata.getColumnTypeName ( 9 );
System.out.println("Column Type: " + ColumnType );
}

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

private void DownRow ( ResultSet DisplayResults ) throws


SQLException
{
ResultSetMetaData metadata = DisplayResults.getMetaData (); int
ColumnWidth;
String printrow;
ColumnWidth = metadata.getColumnDisplaySize ( 9 ) ;
System.out.println("Column Width:" + ColumnWidth);
}
Updating Tables
Modifying data in a database is one of the most common
functionalities in every J2ME application that provides database
interactions.
Generally, any information that is retrievable is also changeable
depending on access rights and data integrity issues

 Update Row and Column


 The UPDATE statement is used to change the value of one or more
columns in one or multiple rows of a table.
 The UPDATE statement must contain the name of the table that is
to be updated and 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.
 The UPDATE statement may have a WHERE clause if a specific
number of rows are to be updated.
Ex:try {
Update Multiple Rows
Multiple rows of a table can be updated by formatting the WHERE
clause expressions to include criteria that qualify multiple rows for the
update.
 Four common WHERE clause expressions are used to update multiple
rows of a table:
 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.
 The IS NULL test Rows that don’t have a value in the specified
column are updated when the IS NULL operator is used in the WHERE
clause expression.
 The comparison test The WHERE clause expression contains a
comparison operator, as described previously in this chapter, that
compares the value in the specified column with a value in the WHERE
clause expression
 All rows A query can direct the DBMS to update the specified column in
Updating a row using the IN test
String query = new String
Update Every Row
("UPDATE Customers " + "SET
String query = new String ("UPDATE
Discount = 25 " + "WHERE
Customers " + "SET Discount = 0 ");
Discount IN (12,15)");

Updating a row using the IS


Update Multiple Columns
NULLtest
String query = new String ("UPDATE
String query = new String
Customers " + "SET Discount = 12,
("UPDATE Customers " + "SET
Street = 'Jones Street'" + "WHERE
Discount = 0 " +
LastName = 'Jones'");
"WHERE LastName IS NULL
");
Update Based on Values in Column Update Using Calculations
String query = new String String query = new String ("UPDATE
("UPDATE Customers " + "SET Customers " + "SET DiscountPrice
Discount = 20 " + = Price * ((100 - Discount) / 100) ");
"WHERE Discount > 20 ");
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.
 Multiple rows can be deleted by including a WHERE clause in the
DELETE FROM statement
 The query that contains the DELETE FROM statement is executed
using the executeQuery() method

Delete a Row from a Table


String query = new String ("DELETE FROM Customers " + "WHERE
LastName = 'Jones' and FirstName = 'Tom'");
Joining Tables Multiple Comparison Join
String query = new String (
Joining two tables "SELECT FirstName,
String query = new String LastName,OrderNumber,
( "SELECT FirstName, LastName, ProductName, Quantity " + " FROM
City, State, ZipCode " + "FROM Customers, Orders, Products " + "
Customers, ZipCode " + WHERE ProdNumber = ProductNumber
"WHERE Zip = ZipCode"); " + " AND CustNumber =
CustomerNumber");
Parent-Child Join Createa Column Name Qualifier
String query = new String (" String query = new String ("SELECT
SELECT OrderNumber, Customers.CustNumber, " + "
ProductName " + FirstName, LastName,
" FROM Orders, Products " + OrderNumber, "
" WHERE ProdNumber = +
ProductNumber"); " ProductName, Quantity " +
" FROM Customers, Orders,
Products "
+ " WHERE ProdNumber =
ProductNumber " +
"AND Customers.CustomerNumber =
Joining Tables
Create a Table Alias
String query = new String ("SELECT c.CustNumber , " + " c.FirstName,
c.LastName, o.OrderNumber, " + " p.ProductName, o.Quantity " +
" FROM Customers c, Orders o, Products p" + " WHERE o.ProdNumber =
p.ProductNumber " + " AND c.CustomerNumber = o.CustomerNumber");

Inner and Outer Joins


There are two kinds of joins, each of which either excludes or includes rows in
both tables of the join that don’t match. These are
■ An inner join excludes rows of either table that don’t have a matching value.
■An outer join includes rows of either table that don’t have a matching value.
inner join
 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
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

 Grouping is the task of organizing rows of data according to similar values


within the same column.
 The GROUP BY clause specifies the name of the column whose values are
used to group rows in the ResultSet.
 ORDER BY

 Sorting is the task of organizing rows of data in either alphabetical or


numerical order according to the value of a column in the result set.
 The ResultSet can be placed in alphabetical or numerical order by using the
ORDER BY clause in the query.
 A simple sort is when the values in a single column are used for the sort.

 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");

Creating groupings and sub groupings in the ResultSet


String query = new String ( " SELECT StoreNumber,SalesRepNumber,
SUM(Sales) " + " FROM Sales " + " Group By StoreNumber,
SalesRepNumber");
Calculate a Subset of Rows
 The DBMS uses the conditional expression to qualify whether or not the
current row should be included in any group of the ResultSet.
 Only rows that meet the condition are returned.

 A row that doesn’t meet the condition is excluded.

 The conditional expression is placed in the HAVING clause of the query.

 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");

Sorting the ResultSet


String query = new String ("SELECT StoreNumber, Sales " + " FROM Sales
"
+ " ORDER BY StoreNumber");
Sorting the ResultSet using major and minor sort keys
String query = new String ("SELECT StoreNumber, Sales " + " FROM Sales
"
+ " ORDER BY StoreNumber, Sales");
Sorting the ResultSet in descending order
String query = new String ("SELECT StoreNumber, Sales " " FROM Sales " +
" ORDER BY StoreNumber DESC ");
Sorting on derived data
String query = new String ( " SELECT StoreNumber, (Sales-Estimate) " + "
FROM Sales " + " ORDER BY 2 ");
Sub queries
 A sub query joins two queries to form one complex query, which efficiently
identifies data to be included in the ResultSet.
 The format of a sub query is similar to a query, but rows that are selected as
a result of the sub query are not returned.
 Instead, selected rows are queried by another query. Rows chosen by the
second query are returned in the ResultSet.
 Both queries and sub queries have a SELECT statement and a FROM
clause and can also include a WHERE clause and HAVING clause to qualify
rows to return.
 Two rules when using a sub query

 Return one column from the subquery. The purpose of a subquery is to


derive a list of information from which a query can choose appropriate rows.
Only a single column needs to be included in the list.
 Don’t sort or group the result from a subquery. Since the ResultSet of
thesubquery isn’t going to be returned in the ResultSet of the query, there is
Creating a sub query
String query = new String (" SELECT StoreNumber " + " FROM Sales "+
" WHERE Estimate = (SELECT SUM(Amount) " + " FROM Orders, Sales "
+ " WHERE StoreNum = StoreNumber) ");
Performing the existence test
String query = new String (" SELECT DISTINCT StoreNumber " + " FROM
Sales "+ " WHERE EXISTS " +" (SELECT StoreNum " + " FROM Orders "
+
" WHERE StoreNum = StoreNumber) ");
Performing the membership test
String query = new String (" SELECT SalesRepNumber " + " FROM Sales
"+ " WHERE StoreNumber IN " + " (SELECT StoreNum " + " FROM Orders
" + " WHERE Estimate < Amount) ");
Performing the any test
String query = new String (" SELECT DISTINCT StoreNumber " + " FROM
Sales "+ " WHERE Estimate > ANY " + " (SELECT Amount" + " FROM
Orders " + " WHERE StoreNumber = StoreNum) ");
Performing the all test
String query = new String (" SELECT DISTINCT Store " + " FROM Sales "+
" WHERE Estimate > ALL " + " (SELECT Amount" + " FROM Orders " +
" WHERE StoreNumber = StoreNum) ");
VIEWs
 We can reduce the complexity of your J2ME application by creating one or
more views of the database for each user ID that is passed to the J2ME
application for data access.
A VIEW is similar to creating a table that contains only data the user ID is
permitted to access.
 A VIEW limits columns and rows that can be queried to specific information
pertaining to a user ID.
 A VIEW is like a filter that hides information from a user ID.
 Each VIEW is uniquely identified with a name and contains selection criteria
for columns and rows that appear in the VIEW when the VIEW is used by a
J2ME component.
Rules for Using VIEWs
■ Restrict access to a table on need-to-know basis.
■ Work with the owner of the data to establish reasonable restrictions.
■Classify users into groups that have similar access requirements to
information.
■ Create a VIEW for each classification of user rather than for each
user.
Creating a VIEW
String query = new String (" CREATE VIEW Store278 AS " + " SELECT * "
+ " FROM Orders " + " WHERE StoreNum = 278");
Selecting columns to appear in a VIEW
String query = new String (" CREATE VIEW StoreProd AS " + " SELECT
StoreNum, ProdNumber " + " FROM Orders
Create a Horizontal VIEW
String query = new String (" CREATE VIEW cust901 AS " + " SELECT * " +
" FROM Orders" + " WHERE CustomerNumber = 901");
Create a Multitable VIEW
String query = new String (" CREATE VIEW ProdDesc AS " + " SELECT
StoreNum, ProdNumber, ProductName " + " FROM Orders, Products "
+ " WHERE ProdNumber = ProductNumber");
Group and Sort VIEWs
String query = new String (" CREATE VIEW GroupProdDesc AS " + "
SELECT StoreNum, ProdNumber, ProductName " +
" FROM Orders, Products " +
" WHERE ProdNumber = ProductNumber" + " ORDER BY
ProdNumber ");
Modify a VIEW

 Update Values in one or more columns of a VIEW are changed to values


supplied by the query.
 Insert A new row is added to the VIEW and indirectly to the underlying
table(s) used to create the VIEW.
 Delete A row is removed from the VIEW and from the underlying table(s)
used to create the VIEW.
 Dropping a VIEW

Two modifiers are used with the DROP VIEW statement:


■CASCADE Remove all VIEWs that depend on the VIEW specified in the
DROP VIEW statement as well as the specified VIEW.
■RESTRICT Remove only the VIEW specified in the DROP VIEW
statement. All dependent VIEWs remain intact.

You might also like