Interview Q&A JDBC
Interview Q&A JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API that communicates
with the database and execute SQLquery.
2) What is a JDBC driver and how many JDBC drivers are available?
JDBC driver contains classes and interfaces that help Java application and database.
1 //for MySQL {
2 try {
3
4 Class.forName ("com.mysql.jdbc.Driver");
5
6 con=DriverManager.getConnection ("jdbc: mysql://localhost:3306/dbanme", "username", "password");
7
8 Statement st=con.createstatement ();
9
10 Resultset rs=st.executeQuery ("select * from user");
11
12 rs.next (); catch (ClassNotFoundException e) {
13
14 System.err.println ("ClassNotFoundException in get Connection," + e.getMessage()); }
15
16 catch (SQLException e) {
17
18 System.err.println ("SQLException in getConnection," + e.getMessage ()) ;}
19
20 //for oracle
21
22 {
23
24 try
25
26 {
27
28 Class.forName ("oracle.jdbc.driver.OracleDriver");
29
30 con= DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:dbname", "username", "password");
31
32 Statement st=con.createstatement();
33
34 Resultset rs=st.executeQuery("select * from user");
35
36 Rs.next();
37
38 } catch (ClassNotFoundException e) {
39
40 System.err.println("ClassNotFoundException in get Connection," +e.getMessage()); }
41
42 catch (SQLException e) {
43
44 System.err.println("SQLException in getConnection, " + e.getMessage()); } return con; }
Code explanation
We need to create a Statement object from above connection object. The statement will
return resultset object. ResultSet.next () means If the result set is still returning row.
1. JDBC API
2. JDBC Driver Manager
3. JDBC Test Suite
4. JDBC-ODBC Bridge
6) What are the JDBC statements?
1. Statement: It will execute SQL query (static SQL query) against the database.
2. Prepared Statement: Used when we want to execute SQL statement repeatedly.
Input data is dynamic and taken input at the run time.
3. Callable Statement: Used when we want to execute stored procedures.
7) How can we execute stored procedures?
Stored procedures can be executed using JDBCcallable statement. Here is the code.
Java
Prepared Statement is used to execute same SQL statements repeatedly. The prepared
statement is compiled only once even though it used “n” number of times
9) What is ResultSet?
The java.sql.ResultSet interface means the result set of a SQL query. It means a cursor
is pointing a row of a table; it points to before the first row.
There are three types of ResultSet is available. If we do not declare any ResultSet that
means we are calling TYPE_FORWARD_ONLY
RowSet extends the ResultSet interface, so it holds all methods from ResultSet. RowSet
is serialized.
So, we can pass Rowset from one class to another class because it has no connection
with the database.
If you want to turn Off the Auto Commit then set connection.setAutoCommit(false)
13) What are database warnings in JDBC and how can we handle database warnings in
JDBC?
No, we cannot get null Resultset. ResultSet.next() can return null if the next record does
not contain a row.
15) What do you mean by Metadata and why we are using it?
Metadata means data or information about other data. We use metadata to get database
product version, driver name, the total number of tables and views.
16) What is the difference between executing, executeQuery, executeUpdate in JDBC?
Connection pooling means connections will be stored in the cache and we can reuse
them in future.
Advantage:
1. It is faster
2. Connection pooling becomes easier to diagnose and analyze database
connection.
18) What is the function of DriverManager class?
It is an interface between user and drivers. DriverManager tracks all the activity between
a database and the appropriate driver.
Batch updates can be used only for insert, update and delete but not for select query.
1. java.sql
2. javax.sql
21) What is the return type of execute, executeQuery and executeUpdate?
No, JDBC-ODBC Bridge uses synchronized methods to serialize all the calls made to
ODBC.
unable to load exact JDBC drivers before calling the getConnection method.
It may be invalid or wrong JDBC URL.
27) Prepared Statements are faster. Why?
Prepared statement execution is faster than direct execution because the statement is
compiled only once. Prepared statements & JDBC driver are connected with each other
during execution, and there are no connection overheads.
28) Is it possible to connect to multiple databases? Using single statement can we update or
extract data from two or three or many databases?
Yes, it is possible to connect to multiple databases, at the same time, but it depends on
the specific driver.
To update and extract data from the different database we can use the single statement.
But we need middleware to deal with multiple databases or a single database.
Defines how many rows a resultset can contain at a time Defines the number of rows that will be read from the d
SELECT NAME FROM TABLE WHERE NAME LIKE ‘\_%’ {escape ‘\’}
Dirty read means “read the value which may be correct or may not be correct.”
Two types of locking are available in JDBC by which we can handle more than one user.
If two users are viewing the same record, then no locking is done. If one user is updating
a record and the second user is also updating the same record. At that time, we are
going to use locking.
1. Optimistic Locking: it will lock the record only when we are going to “update.”
2. Pessimistic Locking: it will lock the record from the “select” to view, update and
commit time.
34) What are the exceptions in JDBC?
1. batchUpdate Exception
2. Data Truncation
3. SQL Exception
4. SQL Warning
35) Give steps to connect to the DB using JDBC?
1. Using DriverManager:
It will load the driver class with the help of class.forName(driver class) and
Class.forName().
2. Using DataSource:
For DataSource, no need to use DriverManager with the help of JNDI. It will lookup the
DataSource from Naming service server. DataSource.getConnection() method will return
Connection object to the DB.
JDBC API supports both 2-tier and 3-tier models for the database.
In 3-tier model commands are redirected to a “middle tier” of services. After that
commands sent to the data source.
37) What are the new features available in JDBC 4.0?
1. sql.Driver
2. Connection
3. Statement
4. PreparedStatement
5. CallableStatement
6. ResultSet
7. ResultSetMetaData
8. DatabaseMetaData
39) How many RowSet are available in JDBC?
A savepoint represents a point that the current transaction can roll back to. Instead of
rolling all its changes back, it can choose to roll back only some of them.
The administrator creates a DataSource object and ties up it with JNDI registry. A
programmer/ developer retrieves the DataSource object from the registry. Then it will
establish the connection with the database.
43) What is the reason why we need a JdbcRowSet like the wrapper around ResultSet?
1. column
2. column index.
updateRow()
deleteRow()
refreshRow()
cancelRowUpdates()
insertRow()
46) Why should we close database connections in Java?
As a best practice, we must close the resultset, the statement and the connection. If the
connection is coming from a pool, on closure, the connection is sent back to the pool for
reuse. We are doing this in the finally{} block, because if any exception occurs, then we
still get the chance to close this.
These are used to store a large amount of data into the database like images, movie,
etc.
Server side cursor means data & results are saved on the server. Only when requested
data is sent to the client.
Client side cursor means all data sent to the client location.
50) How do you insert images into Database using JDBC?
Images in the database using the BLOB datatype wherein the image stored as a byte
stream. Below code is showing how to insert the image into DB.
Java