DEV Community

Saravanan Lakshmanan
Saravanan Lakshmanan

Posted on

Java Learning Series - DB connection with Product Management System

Today, I created DBConnection class to connect database with Java application.

DBConnection.java

package com.company.db;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class DBConnection{

    public static Connection getPSQLConnection(){
        Connection con = null;
        try{
            con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/productdb", "postgres", "saravanan");
            System.out.println("SQL is connected");
        }
        catch(SQLException obj){
            System.out.println("SQL not connected");
        }
    return con;
    }
}
Enter fullscreen mode Exit fullscreen mode

viewProduct() inside ProductService.java

    public void viewProduct() {
            try{
                Connection con = DBConnection.getPSQLConnection();
                String sql = "select * from products";
                PreparedStatement ps = con.prepareStatement(sql);
                System.out.println(ps);
                ResultSet rs = ps.executeQuery();
                System.out.println(rs);
                while(rs.next()){
                    System.out.println(rs.getInt("id"));
                    System.out.println(rs.getString("name"));
                    System.out.println(rs.getString("category"));
                    System.out.println(rs.getInt("price"));    
                }

            }catch(SQLException exe){
                System.out.println("SQLException");
            }
    }
Enter fullscreen mode Exit fullscreen mode

Then, it has been called from Main.java

package com.company.controller;
import com.company.entity.Product;
import com.company.service.ProductService;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileNotFoundException;

public class Main{

    public static void main(String[] args) {

        ProductService service = new ProductService();

        service.viewProduct();
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

SQL is connected
select * from products
org.postgresql.jdbc.PgResultSet@43195e57
1
chair
furniture
10000
2
mobile
electronics
20000

Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
tyriantrade profile image
Tyrian Trade

Great share for beginners! Just a quick tip: remember to close your database connections (or use try-with-resources) to prevent connection leaks. Keep up the good work with this learning series!

Collapse
 
dev_saravanan_journey profile image
Saravanan Lakshmanan

Thank you for your feedback! I'll make sure to close the database connections and explore try with resources in upcoming practice. Appreciate the tip and encouragement!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.