Issue
I am trying to make a simple connection to my postgres database on CentOS 7 ec2 instance. Here is my PostgresqlConnect.java
file:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PostgresqlConnect {
private final static String url = "jdbc:postgresql://rds-service:5432/postgres";
private final static String user = "root";
private final static String password = "test123";
public static void main(String[] args) {
try{
Connection connection = DriverManager.getConnection(url, user, password);
if (connection!= null) {
System.out.println("Connected successfully!");
}
else {
System.out.println("Failed to connect.");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My steps to run/compile are as follows:
> javac -cp /usr/share/java/postgresql-jdbc.jar PostgresqlConnect.java`
> java PostgresqlConnect
And I get this:
-------- PostgreSQL JDBC Connection Testing ------------
java.sql.SQLException: No suitable driver found for jdbc:postgresql://rds-service:5432/postgres
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at PostgresqlConnect.main(PostgresqlConnect.java:15)
I installed the postgresql-jdbc
rpm package as such: yum install postgresql-jdbc
. I think I'm linking the library when I add -cp /usr/share/java/postgresql-jdbc.jar
to my javac -cp /usr/share/java/postgresql-jdbc.jar PostgresqlConnect.java
command so not sure where I'm going wrong. My javac
and java
versions are both 14.0.2
.
Solution
The correct way to run it and see "Connected successfully!" would be
> javac PostgresqlConnect.java
> java -cp /usr/share/java/postgresql-jdbc3.jar PostgresqlConnect.java
Answered By - tbw3 Answer Checked By - Mildred Charles (WPSolving Admin)