Reputation: 3
I've installed postgresql 9.1 for Windows but I can't connect to it using JDBC.
I've downloaded the JDBC jar file and placed it in C:\Program Files\Java\jre7\lib\postgresql-9.1-901.jdbc4.jar, my CLASSPATH is: .;C:\Program Files\Java\jre6\lib\ext\QTJava.zip;C:\Program Files\Java\jre7\lib\postgresql-9.1-901.jdbc4.jar
This is my Java code to create the connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;
import java.io.*;
public class CreateInsert extends Object {
public static void main (String args[]) {
//Create the connection
String driverName = "org.postgresql.Driver";
String connectURL = "jdbc:postgresql://localhost/postgres";
String USERNAME = "postgres";
String PASSWORD = "password";
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection(connectURL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
System.out.println("Error creating class: "+e.getMessage());
System.out.println("The Driver was not found, Please check driver location, classpath, username/password and server url settings");
System.exit(0);
} catch (SQLException e) {
System.out.println("Error creating connection: "+e.getMessage());
System.exit(0);
}
}
}
And I get the error "Error creating class: org.postgresql.Driver"
Any ideas as to what's wrong?
Thanks.
Upvotes: 0
Views: 6538
Reputation: 1109432
I'm using JCreator to compile and run.
The CLASSPATH
environment variable is only used when you use java.exe
command without -cp
, -classpath
and -jar
arguments. Any other way you use to execute the Java application ignores this environment variable. This includes executing the application inside an IDE like Eclipse, Netbeans and JCreator.
In an IDE, you instead need to drop the JAR in the project and add it to the "Build Path" if not done automatically by the IDE yet, depending on the project's structure. This is often a matter of rightclicking the JAR in project and choosing "Add to Build Path" somewhere in the context menu.
Forget about using the CLASSPATH
environment variable. It was a mistake by Sun. They thought to convince starters by avoiding to enter the -cp
or -classpath
arguments everytime for javac
/java
commands. But it end up to be only more confusing to starters as they interpret that environment variable as "the" classpath.
Upvotes: 2
Reputation: 63
The problem is Classpath or the Driver you used. Try to run this using - java -cp C:\Program Files\Java\jre7\lib\postgresql-9.1-901.jdbc4.jar CreateInsert
And send the report
Upvotes: -1