WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java JDBC Β· Advanced Β· question 46 of 100

What is the purpose of the JNDI, and how is it used with JDBC?

πŸ“• Buy this interview preparation book: 100 Java JDBC questions & answers β€” PDF + EPUB for $5

JNDI (Java Naming and Directory Interface) is a standard Java API that provides a naming and directory service for Java applications. Its purpose is to provide a way for Java applications to store and retrieve objects in a hierarchical naming environment, and to locate and access services via a naming system.

When it comes to JDBC, JNDI is commonly used to obtain a JDBC datasource, which is a connection pool of preconfigured database connections that can be reused by applications. Instead of hardcoding the database connection information, applications can use JNDI to look up a datasource that has been configured by the application server or container. This allows for easier management of the database resources and can help to reduce maintenance and development time for complex applications.

Here’s an example of how JNDI can be used with JDBC to obtain a datasource:

    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:/comp/env");
    DataSource datasource = (DataSource) envContext.lookup("jdbc/myDB");
    Connection connection = datasource.getConnection();

In this example, the InitialContext object is used to obtain a reference to the JNDI context, and then the environment context is looked up where the datasource is registered with the name "jdbc/myDB". When a datasource is obtained in this way, the application does not need to worry about the details of how to create or manage the database connections. Instead, it just uses the datasource to obtain a database connection whenever it needs one.

Overall, JNDI makes it easier to manage and locate resources in a Java application, and when used with JDBC, it simplifies the process of obtaining connections to a database.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java JDBC interview β€” then scores it.
πŸ“ž Practice Java JDBC β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java JDBC questions & answers β€” PDF + EPUB for $5

All 100 Java JDBC questions Β· All topics