Java Unit 5
Java Unit 5
1. Java was not considered industrial strength programming language since java was
unable to access the DBMS.
2. Each dbms has its own way to access the data storage. low level code required to
access oracle data storage need to be rewritten to access db2.
3. JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases
4. JDBC drivers has to do the following
• Open connection between DBMS and J2EE environment.
• Translate low level equivalents of sql statements sent by J2EE
component into messages that can be processed by the DBMS.
• Return the data that conforms to JDBC specifications to the JDBC
driver
• Return the error messages that conforms to JDBC specifications to
the JDBC driver
• Provides transaction management routines that conforms to JDBC
specifications to the JDBC driver
• Close connection between the DBMS and the J2EE component.
JDBC Architecture
June 2012 (Briefly discuss the various JDBC driver types 10 M)
JDBC Packages
JDBC API contains two packages. First package is called java.sql, second package is
called javax.sql which extends java.sql for advanced JDBC features.
Explain the various steps of the JDBC process with code snippets.
1. Loading the JDBC driver
• The jdbc driver must be loaded before the J2EE compnet can be connected to
the database.
• Driver is loaded by calling the method and passing it the name of driver
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
2. Connecting to the DBMS.
• Once the driver is loaded , J2EE component must connect to the DBMS using
DriverManager.getConnection() method.
• It is highest class in hierarchy and is responsible for managing driver
information.
• It takes three arguments URL, User, Password
• It returns connection interface that is used through out the process to reference
a database
String url=”jdbc:odbc:JdbcOdbcDriver”;
String userId=”jim”
String password=”Keogh”;
Statement DatRequest;
Private Connection db;
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url,userId,password);
}
3. Creating and Executing a statement.
• The next step after the JDBC is loaded and connection is successfully
made with a particular database managed by the dbms, is to end a
particular query to the DBMS for processing.
• SQL query consists series of SQL command that direct DBMS to do
something example Return rows.
• Connect.createStatement() method is used to create a statement Object.
• The statement object is then used to execute a query and return result
object that contain response from the DBMS
Statement DataRequest;
ResultSet Results;
try {
String query=“select * from Customers”;
DataRequest=Database.createStatement();
Results= DataRequests.executeQuery(query);
}
4. Processing data returned by the DBMS
• java.sql.ResultSet object is assigned the result received from the DBMS
after the query is processed.
• java.sql.ResultSet contain method to interct with data that is returned by
the DBMS to the J2EE Component.
Results= DataRequests.executeQuery(query);
do
{
Fname=Results.getString(Fname)
}
While(Results.next())
In the above code it return result from the query and executes the
query. And getString is used to process the String retrived from the
database.
5 getConnection(String url)
• Sometimes the DBMS grant access to a database to anyone that time
J2EE component uses getConnection(url) method is used.
String url=” jdbc:odbc:JdbcOdbcDriver ”;
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url);
}
6 getConnection(String url, String pass, String user)
• Database has limited access to the database to authorized user and require
J2EE to supply user id and password with request access to the database.
The this method is used.
try{
Class.forName(“sun:jdbc.odbc.JdbcOdbcDriver”);
Db=DriverManager.getConnection(url,userId,password);
}
7 getConnection(String url, Properties prop)
• There might be occasions when a DBMS require information besides
userid and password before DBMS grant access to the database.
• This additional information is called properties and that must be
associated with Properties object.
• The property is stored in text file. And then loaded by load method of
Properties class.
Connection db;
Properties props=new Properties();
try {
FileInputStream inputfile=new FileInputStream(“text.txt”);
Prop.load(inputfile);
}
Write short notes on Timeout:
1. Competition to use the same database is a common occurrence in the J2EE
environment and can lead to performance degradation of J2EE application
2. Database may not connect immediately delayed response because database may not
available.
3. Rather than delayed waiting timeJ2EE component can stop connection. After some
time. This time can bet set with the following method:
DriverManager.setLoginTimeout(int sec).
4. DriverManager.getLoginTimeout(int sec) return the current timeout in seconds.
Explain Connection Pool
1. Client needs frequent that needs to frequently interact with database must either open
connection and leave open connection during processing or open or close and
reconnect each time.
2. Leaving the connection may open might prevent another client from accessing the
database when DBS have limited no of connections. Connecting and reconnecting is
time consuming.
3. The release of JDBC 2.1 Standard extension API introduced concept on connection
pooling
4. A connection pool is a collection of database connection that are opened and loaded
into memory so these connection can be reused with out reconnecting to the
database.
5. DataSource interface to connect to the connection pool. connection pool is
implemented in application server.
6. There are two types of connection to the database 1.) Logical 2.) Physical
7. The following is code to connect to connection pool.
ResultSet
1. ResultSet object contain the methods that are used to copy data from
ResultSet into java collection object or variable for further processing.
2. Data in the ResultSet is logically organized into the virtual table for further
processing. Result set along with row and column it also contains meta data.
3. ResultSet uses virtual cursor to point to a row of the table.
4. J2EE component should use the virtual cursor to each row and the use other
methods of the ResultSet to object to interact with the data stored in column of
the row.
5. The virtual cursor is positioned above the first row of data when the ResultSet
is returned by executeQuery () method.
6. The virtual cursor is moved to the first row with help of next() method of
ResultSet
7. Once virtual cursor is positioned getxxx() is used to return the data. Data type
of data is represents by xxx. It should match with column data type.
8. getString(fname) …..fname is column name.
9. setString(1)……….. in this 1 indicates first column selected by query.
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");/ / rs.getInt(1);
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
DataTruncation
9. Whenever data is lost due to truncation of the data value , a truncation
exception is thrown.
Differentiate between a Statement and a PreparedStatement.
• A standard Statement is used for creating a Java representation for a literal SQL statement
and
for executing it on the database.
• A PreparedStatement is a precompiled Statement.
• A Statement has to verify its metadata in the database every time.