JDBC Questions and Answers
JDBC Questions and Answers
import java.util.List;
import java.util.ArrayList;
import java.util.List;
public StudentDaoImpl(){
students = new ArrayList<Student>();
Student student1 = new Student("Robert",0);
Student student2 = new Student("John",1);
students.add(student1);
students.add(student2);
}
@Override
public void deleteStudent(Student student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from d
atabase");
}
@Override
public Student getStudent(int rollNo) {
return students.get(rollNo);
}
@Override
public void updateStudent(Student student) {
students.get(student.getRollNo()).setName(student.getName());
System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the
database");
}
}
Step 4: Use the StudentDao to demonstrate Data Access Object pattern usage [
DaoPatternDemo.java ]
// update student
Student student =studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);
Output:
ResultSet RowSet
A ResultSet always maintains A RowSet can be connected, disconnected from
connection with the database. the database.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
/**
*
* A Simple example to use CallableStatement in Java Program.
*/
public class Proc {
while(rs.next()){
System.out.println(rs.getString(1));
}
rs.close();
}
}
1. Statement
Statement interface is used to execute normal SQL queries. We can’t pass the
parameters to SQL query at run time using this interface. This interface is preferred
over other two interfaces if we are executing a particular SQL query only once. The
performance of this interface is also very less compared to other two interfaces. In
most of time, Statement interface is used for DDL statements like CREATE, ALTER,
DROP etc.
2. PreparedStatement
/** Setting values to place holders using setter methods of PreparedStatement object *
*/
pstmt.setString(1, "MyName"); /** Assigns "MyName" to first place holder **/
3. CallableStatement
cstmt.execute();
/** Use cstmt.getter() methods to retrieve the result returned by the stored procedure
**/
1. Row and Key Locks: Useful when updating the rows (update, insert or delete
operations), as they increase concurrency.
2. Page Locks: Locks the page when the transaction updates or inserts or deletes
rows or keys. The database server locks the entire page that contains the row. The
lock is made only once by database server, even more rows are updated. This lock
is suggested in the situation where large number of rows is to be changed at once.
3. Table Locks: Utilizing table locks is efficient when a query accesses most of the
tables of a table. These are of two types:
a) Shared lock: One shared lock is placed by the database server, which prevents
other to perform any update operations.
b) Exclusive lock: One exclusive lock is placed by the database server, irrespective
of the number of the rows that are updated.
4. Database Lock: In order to prevent the read or update access from other
transactions when the database is open, the database lock is used.
Functions Procedures
You cannot call stored procedures from a You can call a function from a stored
function procedure.
clearBatch(): This method removes all the statements added with the
addBatch() method.
Connection pooling is performed in the background and does not affect how an
application is coded; however, the application must use a DataSource object (an
object implementing the DataSource interface) to obtain a connection instead of
using the DriverManager class.
The JDBC 3.0 API specifies a ConnectionEvent class and the following interfaces as
the hooks for any connection pooling implementation:
ConnectionPoolDataSource
PooledConnection
ConnectionEventListener
pom.xml
ConnectionPool.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@SuppressWarnings("unused")
public DataSource setUpPool() throws Exception {
Class.forName(JDBC_DRIVER);
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of the
JDBC-ODBC Bridge.
2. Native-API 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.
3. Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully
written in java.
4. Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Driver: This interface handles the communications with the database server. You
will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts the
details associated with working with Driver objects.
Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.
Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
import java.sql.*;
class Rsmd {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.close();
} catch(Exception e){
System.out.println(e);
}
}
}
Output
Total columns: 2
Column Name of 1st column: ID
Methods Description
import java.sql.*;
class Dbmd {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
conn = getConnection();
String query = "insert into nullable_table(id,string_column, int_column) values(?,
?, ?)";
conn.close();
}