In this video I have shown how you can connect to PostgreSQL using JAVA JDBC.
This example is shown in eclipse IDE.
You should download the jar file from official postgresql site.
The jar file shown in this video is postgresql-42.2.9.jar.
You can download it here. postgresql-42.2.9
1. Project Structure.
2. ConnectDB.java
Please update the host,port,dbname,username and password according to your db details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.jinujawad.com; import java.sql.Connection; import java.sql.DriverManager; public class ConnectDB { public static void main(String[] args) { Connection connection = null; String host="localhost"; String port="5432"; String db_name="postgres"; String username="postgres"; String password="root"; try { Class.forName("org.postgresql.Driver"); connection = DriverManager.getConnection("jdbc:postgresql://"+host+":"+port+"/"+db_name+"", ""+username+"", ""+password+""); if (connection != null) { System.out.println("Connection OK"); } else { System.out.println("Connection Failed"); } } catch (Exception e) { e.printStackTrace(); } } } |
3. Before running the code, Please the jar file in the build path.
4.After running the program in Eclipse IDE, The console will show the message the DB Connection is ok.