WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. Book a mock interview →
Basic 17 of 100 · Java JDBC

What is a DataSource, and how is it used in JDBC?

📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

A DataSource is an interface in the Java JDBC API that provides a way to connect to a database. It encapsulates all of the details needed to connect to a database, including the driver and connection properties, and provides a means to obtain a connection to the database. Using a DataSource can simplify the process of connecting to a database since it abstracts away the details of the underlying driver and connection properties.

To use a DataSource in JDBC, you first need to obtain an instance of the DataSource from a JNDI naming service or by creating it programmatically. Once you have a DataSource instance, you can use it to obtain a connection to the database. The process of obtaining a connection from a DataSource typically involves calling the DataSource.getConnection() method, which returns a Connection object.

Here’s an example of how to use a DataSource in JDBC:

    // Obtain a DataSource from JNDI or create one programmatically
    DataSource dataSource = ...;
    
    // Obtain a connection to the database
    Connection connection = dataSource.getConnection();
    
    // Use the connection to execute SQL statements
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");
    
    // Process the results
    while (resultSet.next()) {
        // Do something with each row
    }
    
    // Close the resources
    resultSet.close();
    statement.close();
    connection.close();

In this example, we first obtain a DataSource instance (which is not shown), and then use it to obtain a Connection object. We then use the Connection object to create a Statement and execute a SELECT query. Finally, we process the results and close the resources. By using a DataSource, we abstract away the details of the underlying driver and connection properties.

Line open 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 →
📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

All 100 Java JDBC questions · All topics