Hello! In this article I will write a simple example of connecting to databases in Java. This article is intended for beginners. Here I will describe each line and explain what for.
But first, a little theory.
JDBC (Java DataBase Connectivity - database connection in Java) is designed to interact Java-applications with various database management systems (DBMS). All traffic in JDBC is based on drivers that are specified by a specially described URL.
')
And now practice.
First, create a maven project and place a dependency in pom.xml to connect to the DBMS (In my case, the DBMS will be MySQL):
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> </dependencies>
It should work like this:

Then we connect to the database you need (I use IDEA Ultimate for this, I connect this way).

Further we fill Database, User and Password. Be sure to check the connection.

Next we create the class itself.

And now let's sort it out line by line:
In the beginning we create three variables url, username and password. Sample url instructions:

Username root.Password defaults you need to know yourself.
After using the line Class.forName ("com.mysql.jdbc.Driver") register drivers. Next we establish the connection using DriverManager.getConnection (your url, username, password).
Then, using connection, we create a simple Statement request using the createStatement () method.
Next we create an instance of the ResultSet class and form a request through the statement using the executeQuery method (request).
Then we make the resultSet run across the entire database and output what we need. So, using the resultSet object and its methods (getString, getInt, etc., depending on the type of variables in the column), we derive. Since my query was to print everything, we can output any column.
After we close the resultSet, statement and connection (exactly in this sequence). In the process, it will show errors as it will request exception handling in catch. So write catch in advance.
Now, when there is practice, it is possible to impose a deeper theory on it. The truth is very big, I wish you good luck in studying it.
This project is on github
here .