How to

#JDBC #Java #Interview Questions #Database

JDBC

What is JDBC?

JDBC, Java DataBase Connectivity — an industry standard for connecting Java applications to various databases. It is implemented as part of the java.sql package that comes with Java SE.

JDBC is based on the concept of drivers that enable connecting to a database via a specially defined URL. When the driver is loaded, it registers itself with the system and is automatically invoked when the application requests a URL that contains the protocol for which the driver is responsible.

Back to table of contents

What are the advantages of using JDBC?

The advantages of JDBC include:

Back to table of contents

What is a JDBC URL?

A JDBC URL consists of:

An example of a JDBC URL for connecting to a MySQL database “Test” located at localhost and listening for connections on port 3306 would be: jdbc:mysql://localhost:3306/Test

Back to table of contents

What components make up JDBC?

JDBC consists of two parts:

JDBC converts API-level calls into native commands for a particular database server.

Back to table of contents

List the main classes and interfaces in JDBC.

Back to table of contents

JDBC Type Java Object Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT Boolean
TINYINT Integer
SMALLINT Integer
INTEGER Integer
BIGINT Long
REAL Float
FLOAT Double
DOUBLE Double
BINARY byte[]
VARBINARY byte[]
LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
CLOB Clob
BLOB Blob
ARRAY Array
STRUCT Struct
REF Ref
DISTINCT mapping of base type
JAVA_OBJECT Java base class

Back to table of contents

Describe the main steps for working with the database using JDBC.

Back to table of contents

How do you register a JDBC driver?

A driver can be registered in several ways:

Back to table of contents

How do you establish a connection to a database?

To establish a connection to a database, the static call java.sql.DriverManager.getConnection(...) is used.

You can pass as parameters:

static Connection getConnection(String url)
static Connection getConnection(String url, Properties info)
static Connection getConnection(String url, String user, String password)

As a result of the call, a connection to the database will be established, and an object of the class java.sql.Connection will be created - a sort of “session” within which the further work with the database will occur.

Back to table of contents

What transaction isolation levels are supported in JDBC?

Transaction isolation level - a value that defines how much a transaction is allowed to see uncommitted data, thus indicating the degree of isolation of one transaction from another. A higher isolation level increases data accuracy but may reduce the number of concurrent transactions. Conversely, a lower isolation level allows more concurrent transactions but reduces data accuracy.

When using transactions, to ensure data integrity, the DBMS uses locks to restrict access to data involved in the transaction. Such locks are necessary to prevent:

Transaction isolation levels are defined as constants in the java.sql.Connection interface:

NB! The database server might not support all isolation levels. The java.sql.DatabaseMetaData interface provides information on the transaction isolation levels supported by a specific DBMS.

The isolation level used by the DBMS can be set using the method setTransactionIsolation() of the java.sql.Connection object. You can check the currently applied isolation level using the method getTransactionIsolation().

Back to table of contents

How are database queries formed?

In Java, three interfaces are used for executing database queries:

The objects implementing these interfaces are created using methods from the java.sql.Connection object:

Back to table of contents

What is the difference between Statement and PreparedStatement?

Before execution, the DBMS parses each query, optimizes it, and creates an execution “plan.” If the same query is executed multiple times, the DBMS can cache the execution plan, avoiding the parsing and optimization steps again. This allows the query to execute faster.

In summary, PreparedStatement is advantageous over Statement in that its repeated use with one or multiple parameter sets allows one to take advantage of the precompiled and cached query, while also helping to avoid SQL Injection.

Back to table of contents

How is a database query executed and results processed?

Query execution is performed by invoking methods on the object implementing the java.sql.Statement interface:

An object with the java.sql.ResultSet interface holds the result of the database query - a data set containing a cursor pointing to one of the elements in the set - the current record.

Using the cursor, you can navigate through the data set with the method next().

NB! Immediately after obtaining the data set, its cursor is positioned before the first record, and to make it current, you need to call the next() method.

The fields of the current record can be accessed using the methods getInt(), getFloat(), getString(), getDate(), and similar.

Back to table of contents

How do you call a stored procedure?

Stored procedures are named sets of SQL statements stored on the server. You can call such a procedure from a Java class using the methods of an object implementing the java.sql.Statement interface.

The choice of object depends on the characteristics of the stored procedure:

If you are unsure how the stored procedure is defined, you can use the java.sql.DatabaseMetaData methods to gather information about the structure of the data source, including names and types of parameters.

Example of calling a stored procedure with input and output parameters:

public void runStoredProcedure(final Connection connection) throws Exception {
    // define the stored procedure
    String procedure = "{ call procedureExample(?, ?, ?) }";

    // prepare the statement
    CallableStatement cs = connection.prepareCall(procedure);

    // set input parameters
    cs.setString(1, "abcd");
    cs.setBoolean(2, true);
    cs.setInt(3, 10);

    // describe output parameters
    cs.registerOutParameter(1, java.sql.Types.VARCHAR);
    cs.registerOutParameter(2, java.sql.Types.INTEGER);

    // execute the stored procedure
    cs.execute();

    // obtain results
    String parameter1 = cs.getString(1);
    int parameter2 = cs.getInt(2);

    // finalize the request
    cs.close();
}

Back to table of contents

How do you close the connection to the database?

The connection to the database is closed by calling the close() method on the corresponding java.sql.Connection object or by using the try-with-resources mechanism when creating such an object, which was introduced in Java 7.

NB! You must first close all requests created by this connection.

Back to table of contents

Sources

Back to interview questions