Home Java A simple JDBC example for beginners

A simple JDBC example for beginners

by admin

Hello, In this article I will write a simple example of how to connect to databases in Java for beginners.
But first, a little theory.
JDBC (Java DataBase Connectivity) is designed for Java application interaction with different database management systems (DBMS). All movement in JDBC is based on drivers which are specified by a specially described URL.
And now the practice.
First we create a maven project and in pom.xml put the dependency for the connection to the DBMS (In my case the DBMS will be MySQL):

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependencies><dependency><groupId> mysql</groupId><artifactId> mysql-connector-java</artifactId><version> 5.1.38</version></dependency></dependencies>

It should go like this :
A simple JDBC example for beginners
Next, connect to the database you need (I use IDEA Ultimate, so I connect this way).
A simple JDBC example for beginners
Next, we fill in the Database, User and Password.Be sure to check the connection.
A simple JDBC example for beginners
Next, we create the class itself.
A simple JDBC example for beginners
Now let’s break it down line by line :
At the beginning we create three variables url, username and password. A sample url indication:
A simple JDBC example for beginners
The default Username is root.Password you must know yourself.
After that use the line Class.forName("com.mysql.jdbc.Driver") to register the driver. Next, establish a connection using DriverManager.getConnection (your url, username, password).
After that we use connection to create a simple Statement query using the createStatement() method.
Then we create an instance of ResultSet class and make a statement request using executeQuery method (query).
Next, we make resultSet run through the entire database and output what we need. So with the resultSet object and its methods (getString, getInt, etc. depending on the type of variables in the column) we output.Since my request was to output everything, we can output any column.
After that close resultSet, statement and connection (in that order). During the process it will show errors because it will ask for exception handling in catch.So write catch beforehand.
Now that you have practice, you can put a deeper theory on it.The topic is really a very big one, I wish you good luck in studying it.
This project on github here

You may also like