Connect to MySQL database with JDBC

In this article, we’ll look at connecting the Mysql database, executing queries, and getting / processing the result.

I will use NetBeans to work on the project.

Creating a project

Let’s create bare maven project.

Create new maven project in Netbeans
Create new maven project in Netbeans
Create new maven project in Netbeans (step 2)
Create new maven project in Netbeans (step 2)

Create the Main project class.
Select in Netbeans menu File > New file (CTRL-N)

Creating main class for project in Netbeans
Creating main class for project in Netbeans
Creating main class for project in Netbeans (step 2)
Creating main class for project in Netbeans (step 2)

Project dependencies

Now we need to add dependency jdbc driver.
Current version of connector for java at the moment 5.1.42

Add the following code to pom.xml

Working with jdbc

Work with the database can be divided into five simple steps
Establishing a Connection.
1. First, you need to establish a connection with the database you want to use.  You must manually load any JDBC drivers if you work with version before 4.0.

2. Create a statement.

3. Execute the query.

4. Process the recordset
After the query is executed, we get the ResultSet object to be processed to retrieve the data.

5. Close the connection.
Be sure to close the connection to the database after the end of the work, otherwise there may be a memory leak in your application.

Final project:

Console output:

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.