Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
JDBC API Components | JDBC Overview
Java Data Manipulation with Hibernate
course content

Зміст курсу

Java Data Manipulation with Hibernate

Java Data Manipulation with Hibernate

1. JDBC Overview
2. Fundamentals of Hibernate
3. Final Touches

book
JDBC API Components

Components of JDBC

Every API is composed of components, each responsible for its part of the API's functionality. This structure can also be likened to a production line, where each employee has a role in each process.

For instance, we can logically divide the processes into several sub-processes:

  1. Establish a connection to the database;
  2. Send an SQL query to the database;
  3. Receive data in the form of a response;
  4. Properly interpret this data, adapting it to Java code;
  5. Transform the data into a more convenient data structure (e.g., a list, collection, or map).

For each of these processes, there is a corresponding component responsible for successfully executing its instructions. Let's get acquainted with these components in more detail:

  • Connection: This interface establishes a connection to the database. You use it to create instances of Statement or PreparedStatement;
  • Statement and PreparedStatement: These interfaces are used to execute SQL queries. Statement is used for executing static SQL queries without parameters, while PreparedStatement is designed for executing SQL queries with one or more parameters;
  • ResultSet: When you execute an SQL query to retrieve data (SELECT), the ResultSet stores the retrieved data, allowing you to process each row of the result sequentially;
  • DriverManager: This class manages a list of available JDBC drivers. It selects the appropriate driver when establishing a connection to the database.

So, from this, we can draw a conclusion about how responsibilities are distributed in the code:

  • The DriverManager and Connection classes perform the first process: Establish a connection to the database. The DriverManager selects the appropriate driver for the specific DBMS, and the Connection uses this driver to connect the code to the database;
  • Statement and PreparedStatement handle the second process, as they allow us to send SQL queries to the database and instruct the database on what data we want to retrieve;
  • ResultSet handles the remaining processes. It is with the help of this class and its methods that we can obtain the data in a format convenient for us, such as a List.

Thus, we can see that each of the components serves its purpose. This structure is correct and adheres to SOLID principles.

Note

We will discuss SOLID principles in a separate course. These principles define well-written application code by providing guidelines for writing code correctly.

JDBC Interaction with a Database

Let's examine the interaction of JDBC with a database through code examples.

It may seem complicated at first, but as you progress through the course, especially when working on practical assignments, you will gain a better understanding of how it works and what needs to be done.

To begin with, let's see what the database we will be working with and connecting to looks like. We will be working with the testDatabase schema and the employees table:

A fairly simple table in the database. Now, let's set ourselves the task of retrieving data such as id, name, and salary from the first row in the table (id=1):

Note

You can find instructions on how to properly configure MySQL and retrieve the db_username and db_password here: article.

Let's go through it step by step:

StepActionDescription
1Variable CreationCreate String variables to store the database URL (which includes the database name, equivalent to SQL's USE DatabaseName), the MySQL username, and the user's password. Details are hidden for privacy.
2Connection EstablishmentUse the Connection interface and the DriverManager class to establish a database connection. This involves calling the getConnection() method with the database URL, username, and password as parameters, thereby establishing a connection for sending SQL queries.
3Preparing StatementEmploy the prepareStatement() method on the connection object, and assign the resulting prepared statement object to a variable. This object contains the SQL query specified in the method's parameter.
4Executing QueryUtilize the executeQuery() method on the prepared statement object, assigning the results to a ResultSet object. This object now holds the results of the executed SQL query.
5Retrieving DataCheck for data in the resultSet using the next() method. If data exists, variables are created and assigned values from the first row of the table. The next() method positions us at the 1st row in the table initially, and it's used again to move to subsequent rows.
6Assigning ValuesAssign values to variables by referencing column names, such as id, name, and salary. Values are taken from the FIRST row in the table, with the process repeated for additional rows as needed using the next() method.

The output will look like this:

If we want to display all the elements on the screen, we need to change the if condition to a while loop so that we process each element.

It will look like this:

Output:

Conclusion

For every interaction with a database using JDBC, the same algorithm is used, as shown in the example above. We won't use this exact algorithm frequently because we will use Hibernate to interact with the database, but it's essential for everyone to be aware of this method of database interaction provided by the JDK.

1. What is the primary function of the `Connection` interface in JDBC?
2. Which of the following best describes the `PreparedStatement` in JDBC?
3. What is the role of the `DriverManager` in JDBC?
4. Which JDBC component is responsible for storing and processing data retrieved from a database using a SQL query?
What is the primary function of the `Connection` interface in JDBC?

What is the primary function of the Connection interface in JDBC?

Виберіть правильну відповідь

Which of the following best describes the `PreparedStatement` in JDBC?

Which of the following best describes the PreparedStatement in JDBC?

Виберіть правильну відповідь

What is the role of the `DriverManager` in JDBC?

What is the role of the DriverManager in JDBC?

Виберіть правильну відповідь

Which JDBC component is responsible for storing and processing data retrieved from a database using a SQL query?

Which JDBC component is responsible for storing and processing data retrieved from a database using a SQL query?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt