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;
}
}
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");
}
}
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();
}
}
Output:
SQL is connected
select * from products
org.postgresql.jdbc.PgResultSet@43195e57
1
chair
furniture
10000
2
mobile
electronics
20000
Top comments (3)
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!
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.