0

Here's the code that I wrote for database connection:

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

class StockReduzido {
 // Select "jdbc:postgresql://localhost/tbd" if using a local database

 private static final String LIGACAO ="jdbc:postgresql://localhost:5432/postgres"; //URL
 private static final String UTILIZADOR = "postgres"; //USER
 private static final String SENHA = "meio5"; //PASS
 private static final String INTERROGACAO = "SELECT ref, desig,stock " + "FROM produto WHERE (stock < 5) ORDER BY stock ASC";
 public static void main(String args[])
 throws SQLException {
 Connection objLigacao = null;
 Statement objComando = null;
 ResultSet objResultado = null;
 int intRef = 0;
 String strDesig = "";
 int intStock = 0;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
 objLigacao = DriverManager.getConnection(LIGACAO,
UTILIZADOR, SENHA);
 objComando = objLigacao.createStatement();
 objResultado = objComando.executeQuery(INTERROGACAO);
 while (objResultado.next()) {
 intRef = objResultado.getInt("ref");
 strDesig = objResultado.getString("desig");
 intStock = objResultado.getInt("stock");
 System.out.println("Ref=" + intRef + "; " +
 "Desig=" + strDesig + "; " +
 "Stock=" + intStock + ";");
 }
 objResultado.close();
 objComando.close();
 objLigacao.close();
 }
}

Then I get this error:

java.lang.ClassNotFoundException: org.postgresql.Driver
    at java.lang.Class.forNameImpl(Native Method)
    at java.lang.Class.forName(Class.java:273)
    at StockReduzido.main(StockReduzido.java:24)
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/postgres
    at java.sql.DriverManager.getConnection(DriverManager.java:700)
    at java.sql.DriverManager.getConnection(DriverManager.java:258)
    at StockReduzido.main(StockReduzido.java:28)

My postgres server is localhost:5432. However my database name is 'postgres'. Do I need to make some changes in the URL connection?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Jorge Mendes
  • 77
  • 1
  • 9
  • How do you add the jdbc driver to the classpath? – pirho Oct 24 '17 at 10:45
  • Do you have PostgreSQL JDBC driver in your classpath – Yogi Oct 24 '17 at 10:58
  • How can i Add the JDBC driver to my classpath? I already downloaded and executed the .exe file (postgresql-8.3-607.jdbc2). Do i need to change the environment variables? Or it is something else? – Jorge Mendes Oct 24 '17 at 11:03
  • Please, see the link in my comment: "Possible duplicate", accepted answer describes a lot. – pirho Oct 24 '17 at 11:12

0 Answers0