A Simple JDBC Example for Beginners

Hello! In this article I will write a simple example of connecting to Java databases. This article is intended for beginners. Here I will describe each line to explain why.

But first, a little theory.

JDBC (Java DataBase Connectivity - connection to Java databases) is intended for the interaction of Java applications with various database management systems (DBMS). All traffic in JDBC is based on drivers that are specified by specially described URLs.

And now practice.

First, create a maven project and put a dependency in pom.xml for connecting to the DBMS (in my case, the DBMS will perform MySQL):

mysqlmysql-connector-java5.1.38

It should turn out like this:



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



Next, fill in Database, User and Password. Be sure to check the connection.



Next we create the class itself.



And now we will analyze it line by line:

In the beginning we create three variables url, username and password. Sample url:



Username is the default root.Password you should know yourself.

After using the line Class.forName ("com.mysql.jdbc.Driver") we register the drivers. Next, establish a 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 query through statement using the executeQuery method (query).

Next, we make resultSet go over the entire database and display what we need. So using the resultSet object and its methods (getString, getInt, etc., depending on the type of variables in the column), we print. Since my request was to display everything, we can print any column.

After we close resultSet, statement and connection (in that sequence). In the process, it will show errors as it will request exception handling in catch. So write catch in advance.

Now that practice is there, a deeper theory can be imposed on it. The theme is really very big, I wish you good luck in studying it.

This github project is here.

Also popular now: