Set 5 - Javatpoint - JDBC IQ
Set 5 - Javatpoint - JDBC IQ
A list of top frequently asked JDBC interview questions and answers is given
below.
1) What is JDBC?
JDBC is a Java API that is used to connect and execute the query to the
database. JDBC API uses JDBC drivers to connect to the database. JDBC API
can be used to access tabular data stored into any relational database.
More details.
1. JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver uses the ODBC
driver to connect to the database. The JDBC-ODBC bridge driver converts
JDBC method calls into the ODBC function calls. This is now discouraged
because of the thin driver. It is easy to use and can be easily connected to
any database.
2. Native-API driver (partially java driver): The Native API driver uses the
client-side libraries of the database. The driver converts JDBC method calls
into native calls of the database API. It is not written entirely in Java. Its
performance is better than JDBC-ODBC bridge driver. However, the native
driver must be installed on each client machine.
3. Network Protocol driver (fully java driver): The Network Protocol driver
uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is entirely written in
Java. There is no requirement of the client-side library because of the
application server that can perform many tasks like auditing, load balancing,
logging, etc.
4. Thin driver (fully java driver): The thin driver converts JDBC calls directly
into the vendor-specific database protocol. That is why it is known as the thin
driver. It is entirely written in Java language. Its performance is better than all
other drivers however these drivers depend upon the database.
More details.
The forName() method of the Class class is used to register the driver
class. This method is used to load the driver class dynamically.
Consider the following example to register OracleDriver class.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
o Creating connection:
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
1. Statement stmt=con.createStatement();
o Closing connection:
1. con.close();
More details.
Interfaces:
Classes:
o Blob: Blob stands for the binary large object. It represents a collection of
binary data stored as a single entity in the database management system.
o Clob: Clob stands for Character large object. It is a data type that is used by
various database management systems to store character files. It is similar to
Blob except for the difference that BLOB represent binary data such as
images, audio and video files, etc. whereas Clob represents character stream
data such as character files, etc.
Statements Explanation
Statement Statement is the factory for resultset. It is used for general purpose
access to the database. It executes a static SQL query at runtime.
Statement PreparedStatement
In the case of Statement, the query is compiled In the case of PreparedStatement, the
each time we run the program. query is compiled only once.
The Statement is mainly used in the case when PreparedStatement is used when we
we need to run the static query at runtime. need to provide input parameters to
the query at runtime.
More details.
Type Description
ResultSet.TYPE_SCROLL_INSENS The cursor can move in both the direction (forward and
ITIVE backward). The ResultSet is not sensitive to the changes
made by the others to the database.
ResultSet.TYPE_SCROLL_SENSIT The cursor can move in both the direction. The ResultSet
IVE is sensitive to the changes made by the others to the
database.
ResultSet RowSet
1. Class.forName("oracle.jdbc.driver.OracleDriver");
2. Connection con=DriverManager.getConnection(
3. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
1. stmt.setInt(1,1011);
2. stmt.setString(2,"Amit");
3. stmt.execute();
o Check the database; the values will be found there. However, the
complete code will look like the following.
1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10.stmt.setInt(1,1011);
11.stmt.setString(2,"Amit");
12.stmt.execute();
13.
14.System.out.println("success");
15.}
16.}
More details.
15) What are the functions of the JDBC Connection interface?
The Connection interface maintains a session with the database. It can be
used for transaction management. It provides factory methods that return
the instance of Statement, PreparedStatement, CallableStatement, and
DatabaseMetaData.
More details.
More details.
More details.
1. import java.sql.*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=con.getMetaData();
10.
11.System.out.println("Driver Name: "+dbmd.getDriverName());
12.System.out.println("Driver Version: "+dbmd.getDriverVersion());
13.System.out.println("UserName: "+dbmd.getUserName());
14.System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
15.System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion
());
16.
17.con.close();
18.}catch(Exception e){ System.out.println(e);}
19.}
20.}
Output
More details.
20) What is batch processing and how to perform batch
processing in JDBC?
By using the batch processing technique in JDBC, we can execute multiple
queries. It makes the performance fast. The java.sql.Statement and
java.sql.PreparedStatement interfaces provide methods for batch processing.
The batch processing in JDBC requires the following steps.
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:x
e","system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.addBatch("insert into user420 values(190,'abhi',40000)");
10.stmt.addBatch("insert into user420 values(191,'umesh',50000)");
11.
12.stmt.executeBatch();//executing the batch
13.
14.con.commit();
15.con.close();
16.}}
More details.
21) What are CLOB and BLOB data types in JDBC?
BLOB: Blob can be defined as the variable-length, binary large object which
is used to hold the group of Binary data such as voice, images, and mixed
media. It can hold up to 2GB data on MySQL database and 128 GB on Oracle
database. BLOB is supported by many databases such as MySQL, Oracle, and
DB2 to store the binary data (images, video, audio, and mixed media).
o Row and Key Locks: These type of locks are used when we update the
rows.
o Page Locks: These type of locks are applied to a page. They are used in the
case, where a transaction remains in the process and is being updated,
deleting, or inserting some data in a row of the table. The database server
locks the entire page that contains the row. The page lock can be applied
once by the database server.
o Table locks: Table locks are applied to the table. It can be applied in two
ways, i.e., shared and exclusive. Shared lock lets the other transactions to
read the table but not update it. However, The exclusive lock prevents others
from reading and writing the table.
o Database locks: The Database lock is used to prevent the read and update
access from other transactions when the database is open.
23) How can we store and retrieve images from the database?
By using the PreparedStatement interface, we can store and retrieve images.
Create a table which contains two columns namely NAME and PHOTO.
1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
11.ps.setString(1,"sonoo");
12.
13.FileInputStream fin=new FileInputStream("d:\\g.jpg");
14.ps.setBinaryStream(2,fin,fin.available());
15.int i=ps.executeUpdate();
16.System.out.println(i+" records affected");
17.
18.con.close();
19.}catch (Exception e) {e.printStackTrace();}
20.}
21.}
Consider the following example to retrieve the image from the table.
1. import java.sql.*;
2. import java.io.*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10.PreparedStatement ps=con.prepareStatement("select * from imgtable");
11.ResultSet rs=ps.executeQuery();
12.if(rs.next()){//now on 1st row
13.
14.Blob b=rs.getBlob(2);//2 means 2nd column data
15.byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
16.
17.FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");
18.fout.write(barr);
19.
20.fout.close();
21.}//end of if
22.System.out.println("ok");
23.
24.con.close();
25.}catch (Exception e) {e.printStackTrace(); }
26.}
27.}
More details.
Java Code
1. import java.io.*;
2. import java.sql.*;
3.
4. public class StoreFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11.PreparedStatement ps=con.prepareStatement(
12."insert into filetable values(?,?)");
13.
14.File f=new File("d:\\myfile.txt");
15.FileReader fr=new FileReader(f);
16.
17.ps.setInt(1,101);
18.ps.setCharacterStream(2,fr,(int)f.length());
19.int i=ps.executeUpdate();
20.System.out.println(i+" records affected");
21.
22.con.close();
23.
24.}catch (Exception e) {e.printStackTrace();}
25.}
26.}
The example to retrieve the file from the Oracle database is given below.
1. import java.io.*;
2. import java.sql.*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11.PreparedStatement ps=con.prepareStatement("select * from filetable");
12.ResultSet rs=ps.executeQuery();
13.rs.next();//now on 1st row
14.
15.Clob c=rs.getClob(2);
16.Reader r=c.getCharacterStream();
17.
18.FileWriter fw=new FileWriter("d:\\retrivefile.txt");
19.
20.int i;
21.while((i=r.read())!=-1)
22.fw.write((char)i);
23.
24.fw.close();
25.con.close();
26.
27.System.out.println("success");
28.}catch (Exception e) {e.printStackTrace(); }
29.}
30.}
Must not have the return type. Must have the return type.
The procedure supports input and output The function supports only input parameter.
parameters.
Exception handling using try/catch block can Exception handling using try/catch can't be
be used in stored procedures. used in user-defined functions.
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:x
e","system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10.stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12.con.commit();
13.con.close();
14.}}
o JdbcRowSet
o CachedRowSet
o WebRowSet
o JoinRowSet
o FilteredRowSet