MAD Unit4
MAD Unit4
MAD Unit4
Record Management
System
Contents
Record Management System – Introduction
Record Storage in RMS
Creating a new record and Reading existing record
Writing & Reading records of Mixed Data Type
Record Enumeration
Searching Records –Single Data Type
Sorting Mixed Data type records in a record enum
Record Listener
Introduction
RMS is used for Maintaining the database in small computing devices
RMS maintains record-oriented database (RMS) stored in Flash mem
Device-independent API
Records are arrays of bytes that live in record stores
Record stores are shared within MIDlet suite
MIDP 2.0 allows for optional sharing of record stores between
MIDlet suites
Support for enumeration, sorting, and filtering
Atomic update for single records
Introduction (cont..)
removeRecordStore(name)
RecordStore
Int getSizeAvailable() – get amount of space available for
public ReadWrite()
{
openRecStore(); // Create the record store
try
{
rs.addRecord(rec, 0, rec.length);
}
catch (Exception e)
{
db(e.toString());
}
}
RMSMidlet for Read Write
public int numRecords() Returns the number of records
available in this enumeration's set.
public byte[]previousRecord() Returns a copy of
the previous record in this enumeration, where
public intpreviousRecordId() Returns the recordId of
the previous record in this enumeration,
public voidrebuild() Request that the enumeration be updated to
reflect the current record set.
Record Filter
The Sorting with a comparator is one option when working with an enumerator,
searching with a filter is the other. A minor difference between a comparator
and a filter is that a comparator returns the entire record store in sorted order,
whereas a filter returns only those records that match a specified criteria.
If you apply both a comparator and a filter, records that match the search
criteria will be returned in sorted order.
Like the RecordComparator, the RecordFilter is implemented by the addition of a
single method, matches(), to the enumerator code.
The enumerator calls the matches() method for each record in the store. Based
on the boolean return value, the record either becomes a member of the result
set or is tossed aside as a record that does not meet the search criteria.
Method for RecordFilter API
boolean matches(byte[] candidate)
Searching Single Data Type records
Example
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
RecordAdded
public void recordAdded(RecordStore recordStore, int recordId)
Called when a record has been added to a record store
Parameters:
recordStore - the RecordStore in which the record is stored.
recordId - the recordId of the record that has been added.
Record Listener(cont..)
RecordChanged
public void recordChanged(RecordStore recordStore, int recordId)
Called after a record in a record store has been changed. If the implementation
of this method retrieves the record, it will receive the changed version.
Parameters:
recordStore - the RecordStore in which the record is stored.
recordId - the recordId of the record that has been changed.
RecordDeleted
public void recordDeleted(RecordStore recordStore, int recordId)
Called after a record has been deleted from a record store. If the
implementation of this method tries to retrieve the record from the record store,
an InvalidRecordIDException will be thrown.
Parameters:
recordStore - the RecordStore in which the record was stored.
recordId - the recordId of the record that has been deleted.
Important Questions
1. Explain the features of RMS
2. Explain the operations of RMS with example
3. Explain Record Enumeration and its methods
4. Explain searching Mixed Data Type records of a
Record Store
5. Explain sorting single data type records of Record
Store
6. Explain RecordListener Interface
UNIT IV Chapter-I I
JDBC
Overview
46
GenaralArchitecture
JDBC Driver
Types
Type 1
JDBC-ODBC Bridge
Type 2
Native API, partially java
Type 3
JDBC Network Driver, partially java
Type 4
100% Java
Type 1 Driver
Translate JDBC calls into ODBC calls
and use Windows ODBC built in drivers
ODBC must be set up on every client
Then ODBC calls are mapped to
respective DBMS specific calls
Type 1 Driver (cont.)
Vendor
Library
Type 2 Drivers
Converts JDBC to data base vendors
native SQL calls
Type 2 Drivers (cont.)
Client JDBC DB
Vendor
Library
Type 3 Drivers
Translates JDBC to a DBMS
independent network protocol
Typically talks directly with a
middleware product which in turn talks
to the RDBMS
Most flexible driver type
all java
Type 3 Drivers (cont.)
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
56
1. Establish a connection
import java.sql.*;
Load the vendor specific driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver");
dynamically loads a driver class
Make the connection
Connection con = DriverManager.getConnection(
"jdbc:odbc:DSN", username, passwd);
57
2. Create JDBC statement(s)
Statement stmt = con.createStatement() ;
Creates a Statement object for sending SQL
statements to the database
58
3. Executing SQL Statements
String query = “select * from emp";
ResultSet rs=stmt.executeQuery(query);
Resultset stores the records returned by the
query
59
4. Get ResultSet
while (rs.next()) {
int ssn = rs.getInt(“EMPNO");
String name = rs.getString(“ENAME");
}
60
5.Close connection
stmt.close();
con.close();
61
Sample program
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //dynamic loading of driver
62
Sample program(cont)
ResultSet rs = s.getResultSet();
while ( rs.next() )
{
System.out.println("Data from column_name: " + rs.getString(1) );
}
s.close(); // close Statement to let the database know we're done with
it
con.close(); //close connection
}
catch (Exception err) { System.out.println("ERROR: " + err); }
}
}
63
Statement Objects
Once a connection is obtained we can interact with the database.
Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three
execute methods.
boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved;
otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly
dynamic SQL.
int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL
statement. Use this method to execute SQL statements for which you expect to get a number of rows
affected - for example, an INSERT, UPDATE, or DELETE statement.
ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to
get a result set, as you would with a SELECT statement.
The first marker represents position 1, the next position 2, and so forth.
All of the Statement object's methods for interacting with the database (a)
execute(), (b) executeQuery(), and (c) executeUpdate() also work with the
PreparedStatement object.
However, the methods are modified to use SQL statements that can take input
the parameters.
PreparedStatement Example
//Selecting Records using PreparedStatement
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
IN
A parameter whose value is unknown when the SQL statement is created. We bind values
to IN parameters with the setXXX() methods.
OUT
A parameter whose value is returned by the SQL statement. We can get the value from
the OUT parameters with the getXXX() methods.
INOUT
A parameter acts as both input and output values. We can bind variables with
the setXXX() methods and retrieve values with the getXXX() methods.
CallableStatement Example
Stored Procedure:
CREATE OR REPLACE PROCEDURE getName(EMP_ID IN NUMBER, E_NAME
OUT VARCHAR) AS BEGIN SELECT name INTO E_NAME FROM Employee
WHERE ID = EMP_ID; END;
TYPE_FORWARD_ONLY:
The result set cannot be scrolled; its cursor moves forward only, from before the first
row to after the last row. The rows contained in the result set depend on how the
underlying database generates the results. That is, it contains the rows that satisfy the
query at either the time the query is executed or as the rows are retrieved.
ResultSet(cont..)
TYPE_SCROLL_INSENSITIVE:
The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an
absolute position. The result set is insensitive to changes made to the
underlying data source while it is open. It contains the rows that satisfy
the query at either the time the query is executed or as the rows are
retrieved.
TYPE_SCROLL_SENSITIVE:
The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an
absolute position. The result set reflects changes made to the
underlying data source while the result set remains open.
The default ResultSet type is TYPE_FORWARD_ONLY.
JDBC – Scrollable Result Set
…
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
…
Statement stmt =
con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
String query = " select students, grade from class
where type=‘really listening this presentation’ “;
ResultSet rs = stmt.executeQuery( query );
…
while ( rs.next() )
{
int grade = rs.getInt(“grade”);
rs.updateInt(“grade”, grade+10);
rs.updateRow();
}
74
Transaction Processing
JDBC allows SQL statements to be grouped together into a
single transaction
Transaction control is performed by the Connection object,
default mode is auto-commit, I.e., each sql statement is
treated as a transaction
We can turn off the auto-commit mode with
con.setAutoCommit(false);
And turn it back on with con.setAutoCommit(true);
Once auto-commit is off, no SQL statement will be
committed until an explicit is invoked con.commit();
At this point all changes done by the SQL statements will be
made permanent in the database.
75
Metadata
A Connection's database is able to
provide schema information describing
its tables, its supported SQL grammar,
its stored procedures the capabilities of
this connection, and so on
ResultSet rs =
dbmd.getTables(catalog , schema , table , types );
…
77
JDBC – Metadata from RS
public static void printRS(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
// get number of columns
int nCols = md.getColumnCount();
// print column names
for(int i=1; i < nCols; ++i)
System.out.print( md.getColumnName( i)+",");
/ / output resultset
while ( rs.next() )
{ for(int i=1; i < nCols; ++i)
System.out.print( rs.getString( i)+",");
System.out.println( rs.getString(nCols) );
}
} 78
Data Types
79
Exceptions
java.sql.SQLException extends the java.lang.Exception class
MODEL Programs
Tables & Indexing.
Inserting , Selecting , Deleting & Updating data of Tables
Joining Tables
Calculating Data
Grouping and Ordering Data ,Sub Queries
VIEWS
Model Programs
Many programming styles can be used to write the data-access
portion of a J2ME component.
Two programming styles—
Model A and Model B programs
Drop Table
Drop an Index
An existing index can be removed from the database by using the DROP
Inserting data into Table
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.
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();
}
Call the CURRENT_TIME() function whenever a column requires the current time.
Atimestamp consists of both the current date and time and is used in applications where both date
and time are
Selecting Data
Selecting Data from a Table
Retrieving information from a database
is the most frequently used routine of
J2ME components that interact with a
database.
executeQuery() method is used to
retrieve the data and returns a
ResultSet.
Therefore, use the Model B program
Selecting Data(cont..)
Selecting All data
try {
String query = new String ("SELECT " +
" FirstName, LastName, Street, City, State, ZipCode " +
" FROM Customers");
DataRequest = Database.createStatement();
Results = DataRequest.executeQuery (query);
DisplayResults (Results);
DataRequest.close(); }
private void DownRow ( ResultSet DisplayResults ) throws
SQLException
{
String FirstName= new String(); String LastName= new String();
String Street= new String(); String City = new String();
String State = new String(); String ZipCode= new String();
String printrow;
FirstName = DisplayResults.getString ( 1 ) ; LastName =
DisplayResults.getString ( 2 ) ;
Street = DisplayResults.getString ( 3 ) ; City = DisplayResults.getString
(4);
Select
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.
Ex:
String query = new String ("SELECT FirstName, LastName " +" FROM Customers "
+" WHERE LastName = 'Jones' " +" AND FirstName = 'Bob'");
The rows are retrieved whose First name should be Bob and last name should be
Jones
AND Clause
The AND clause tells 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 your program.
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 that the
compound expression evaluates to a boolean true if either of the two
subexpressions evaluates to a boolean true.
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.
Equal, Not Equal, Less than , Greater
than, Between operators
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.
Ex:
"SELECT " +"FirstName, LastName, Street, City, State, ZipCode, Sales " +"FROM
Customers " +"WHERE NOT Sales = 50000 “
Retrieves those records whose sales are not 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 and Greater Than or Equal To
Ex: Less Than or Equal To
String query = new String ("SELECT " + "FirstName, LastName, Street, City,
State, ZipCode, Sales " + "FROM Customers " +"WHERE Sales <= 50000 " );
Between Operator
Used to specify the range which includes the lower limit value and also
upper limit value
SELECT " +"FirstName, LastName, Street, City, State, ZipCode, Sales " +"FROM
Customers " +
Like ,IS NULL operators
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
Underscore (_) A single-character wildcard character.
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:
"SELECT " +"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM
Customers " +"WHERE LastName LIKE 'Smi%' ");
Retrieves the rows whose last name first 3 characters are Smi and the rest can be
any thing
IS NULL Operator
The IS NULL operator is used to determine whether a specified column does not contain any
value.
Ex:
"SELECT " +"FirstName, LastName, Street, City, State, ZipCode, Sales " + "FROM Customers " +
Metadata
Meta Data
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.
Metadata can be used in a J2ME application for various purposes,
such as to display the column name of a column and determine the data type of a column.
The most commonly used metadata are.
Column name
Column number
Column data type
Column width
Number of Columns in ResultSet
Example code:
ResultSetMetaData metadata = DisplayResults.getMetaData ();
No. Of Columns
int NumberOfColumns;
NumberOfColumns = metadata.getColumnCount ();
Meta Data(cont..)
Data Type of Column
Name of Column
String ColumnName = new String();
Column Size
The column size, also referred to as the column width, is called the display size
and represents the number of characters needed to display the maximum
value that might be stored in the column.
int ColumnWidth;
ColumnWidth = metadata.getColumnDisplaySize ( 9 ) ;
Update
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– here 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 –Here the WHERE clause expression contains a comparison operator
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 all rows of a table
by excluding the WHERE clause in the query.
Update(cont..)
Ex:
IN Test
try {
String query = new String ("UPDATE Customers " + "SET
Discount = 25 " + "WHERE Discount IN (12,15)");
DataRequest = Database.createStatement();
DataRequest.executeUpdate (query);
DataRequest.close(); }
IS NULL Test
try {
String query = new String ("UPDATE Customers " + "SET
Discount = 0 " + "WHERE LastName IS NULL ");
DataRequest = Database.createStatement();
DataRequest.executeUpdate (query);
DataRequest.close(); }
Update (cont..)
Update Based on Values in Column
try {
String query = new String ("UPDATE Customers " + "SET Discount = 20 " +
"WHERE Discount > 20 ");
DataRequest = Database.createStatement(); DataRequest.executeUpdate (query);
DataRequest.close();
}
Before you delete a row from a table, you must be certain that
other tables are not negatively affected.
Multiple rows can be deleted by including a WHERE clause in
the DELETE FROM statement,
try {
String query = new String ("DELETE FROM Customers " +
"WHERE LastName = 'Jones' and FirstName = 'Tom'");
DataRequest = Database.createStatement();
DataRequest.executeUpdate (query);
DataRequest.close();
}
Joining Tables
How rows of data elements that are placed in tables are related to
each other by linking rows using a common value in each row of two
tables.
In this example, the DBMS is directed to join rows of the Products table and rows of the
Orders table. There are two components of the subexpression in this example. The first
requires the DBMS to match product numbers in both tables. The other subexpression
requires that the value in the
Quantity column is greater than 2.
try {
String query = " SELECT OrderNumber, ProductName, Quantity " +" FROM Orders, Products "
+" WHERE ProdNumber = ProductNumber " + " AND Quantity > 2";
DataRequest = Database.createStatement(); Results = DataRequest.executeQuery (query);
Joining(cont..)
Multitable Join
More than two tables can be joined together by
using the name of each table in the join in the
FROM clause and by defining the join with the
appropriate column names in the WHERE clause
expression.
try {
String query = new String (
"SELECT FirstName, LastName,OrderNumber,
ProductName, Quantity " +" FROM Customers,
Orders, Products " +
" WHERE ProdNumber = ProductNumber " +" AND
CustNumber = CustomerNumber");
DataRequest = Database.createStatement();
Column Name Qualifier
Create a Column Name Qualifier
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 includedin the
join.
Ex:
Left outer join
try {
String query = new String (" SELECT FirstName, LastName,OrderNumber "
+" FROM Customers LEFT JOIN Orders " +
" ON Customers.CustNumber = Orders.CustomerNumber");
}
Right Outer Join
try {
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:
Ex:
SUM()
Grouping and Ordering
Columns are returned in the ResultSet in the order that the column names appear in the
SELECT statement of the query.
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
The GROUP BY clause specifies the name of the column whose values are used to group rows
in the ResultSet.
EX:
In this example the GROUP BY clause organizes the ResultSet by the value in the StoreNumber
column.
This means that the ResultSet contains the sum of the Sales column for each StoreNumber.
try {
String query = new String (" SELECT StoreNumber, SUM(Sales) " + " FROM Sales " +" Group
By StoreNumber");
DataRequest = Database.createStatement();Results = DataRequest.executeQuery (query);
System.out.println("Store Sales");System.out.println("----- -----");
DisplayResults (Results);DataRequest.close();
}
Group By (cont..)
Group Multiple Columns
The DBMS can create a subgroup within a
group in the ResultSet.
For example, the business unit may want to
see orders organized by store, and within
each store, orders are organized by
product.
try {
String query = new String (" SELECT
StoreNumber,SalesRepNumber,
SUM(Sales) " +
Group By(cont..)
Conditional Grouping
The number of rows that are included in a
group can be limited by a conditional
expression in the query.
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.
try {
String query = new String ("SELECT
StoreNumber, SUM(Sales) " + " FROM
Order
Sorting Data
By Clause
The ResultSet can be placed in alphabetical or numerical order
by using the ORDER BY clause in the query.
In this example, The ORDER BY clause specifies the
StoreNumber column, which sorts the value of the StoreNumber
column in ascending numerical order
try {
String query = new String ("SELECT StoreNumber, Sales " +"
FROM Sales " +
" ORDER BY StoreNumber");
DataRequest = Database.createStatement();Results =
DataRequest.executeQuery (query);
System.out.println("Store Sales");System.out.println("----- -----
");
DisplayResults (Results); DataRequest.close();
}
By default the data is sorted in ascending order
Sub Queries
Create a Subquery
EX:
Here the subquery joins rows of the Sales table and the Order
table by store number value, as shown in the second WHERE
clause.
Once joined, the subquery totals the value of the Amount
column for each store number and returns the results to a
temporary table.
try {
String query = new String (" SELECT StoreNumber " +" FROM
Sales "+ " WHERE Estimate = (SELECT SUM(Amount) " + "
FROM Orders, Sales " +" WHERE StoreNum = StoreNumber) ");
VIEWS
You 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.
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.
Once a VIEW is created, the J2ME application references a VIEW the same way that a
table is referenced in a query.
Rules for Using VIEWs
Views (cont..)
In many situations, using VIEWs increases the efficiency of interacting with tables in a
database. However, there are times when VIEWs are not appropriate for an application. The
following is a set of rules that govern how you should use VIEWs in your application:
· Create as many VIEWs as necessary to simplify access to a database.
· 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.
· More than one column can be used in a VIEW.
· More than one table can be used in a VIEW.
· A VIEW is treated as a table in a query regardless of the number of columns and
tables
that are used to create the VIEW.
· Use a VIEW whenever your program accesses some columns in many tables.
· The view simplifies the number of tables that a J2ME application needs to access
directly.
Beware of data security restrictions that affect the underlying columns and tables used to
create the VIEW.
AVIEW inherits data security restrictions from tables used to create the VIEW. Therefore, if
the user ID doesn’t have rights to information in a table, the VIEW also has the same
restrictions.
Views (cont..)
Create a VIEW
AVIEW is created by using the CREATE VIEW statement, as illustrated in
try {
String query = new String (" CREATE VIEW Store278 AS " +" SELECT * " +
" FROM Orders " +" WHERE StoreNum = 278");DataRequest = Database.createStatement();
}
A View can be used to update columns and rows in the underlying tables that comprise the View.
However, updating a View is possible only if you adhere to a set of rules that govern the use of
updating a View.
Calculation, expressions, and built-in column functions cannot be used in the SELECT
statement of the VIEW. Instead, only names of columns can be used.
Exclude the GROUP BY clause and HAVING clause from the VIEW.
Duplicate rows must be included in the modification.
You cannot use the DISTINCT modifier in the VIEW if values of the view are going to be
modified.
Subqueries cannot be used in a VIEW if rows of the VIEW are to be modified.
Views (cont..)
Updating a View
try {
String query = new String (" UPDATE Store278 " + " SET Amount = 700 " +" WHERE
OrderNumber = 334 ");
}
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.
Ex: "SELECT " + "FirstName, LastName, Street, City, State, ZipCode,
Sales " + " FROM Customers " +" WHERE Sales IN (20000, 30000,
40000) "
NOT IN Modifier