Postgresql JDBC Connection Error - java

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.

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.

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

Related

No Suitable Driver error after setting CLASSPATH, Maven, and pom.xml

Since yesterday I have been trying to figure out how to fix this SQLException, and at this point I'm empty. I have checked dozens of sites, the whole documentation for Microsoft and Azure on how to connect with databases, and I keep getting the same error.
I've added a CLASSPATH like CLASSPATH =.;C:\Program Files\Microsoft JDBC Driver 8.2 for SQL Server\sqljdbc_8.2\enu\mssql-jdbc-8.2.2.jre11.jar as informed on Using the JDBC Driver documentation. I've downloaded the JDBC driver from Microsoft themselves and dumped the files on a folder in C:\Program Files\Microsoft JDBC DRIVER 8.4 for SQL Server as their documentation suggests. My maven and java are working fine, and I have an example class that I've got from SQLExamples by Microsoft themselves, this one:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// As informed on:
// https://www.microsoft.com/en-us/sql-server/developer-get-started/java/windows/step/2.html
public class App {
public static void main(String[] args) {
String connectionUrl = "jdbc:sqlserver:[AzureAddressHere];"
+ "database=[DatabaseHere];"
+ "user=[UserHere];"
+ "password=[PasswordHere]";
try {
// Load SQL Server JDBC driver and establish connection.
System.out.print("Connecting to SQL Server ... ");
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
System.out.println("Done.");
}
} catch (SQLException e) {
System.out.println();
e.printStackTrace();
}
}
}
I've also added the references to the jar file to the pom.xml dependencies list:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.4.1.jre11</version>
</dependency>
I've also found a mention in a website that the jar file sits in Maven's library folder, so I've copied the jar file to the lib folder as well.
Yet, whenever I try to run the app, I get the java.sql.SQLException: No suitable driver found for [AzureInformation].
Any ideas on what I could be missing here?
Turns out that the issue was the lack of two // in the address. facepalm
So, I just set this line to: String connectionUrl = "jdbc:sqlserver://[AzureAddressHere];" and it finally connected.
To be fair to myself here, this error is so completely unclear and unhelpful.

Running java class with library from cmd

I have a Baseloader.java class which makes use of Postgresql database, and I have a postgresql42.jar file which handles the jdbc stuff.
Baseloader.java
import java.sql.Connection;
import java.sql.DriverManager;
public class Baseloader
{
public static void main(String[] args)
{
System.out.println("Hello, sir!");
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/my_base",
"postgres", "123");
System.out.println("Done, sir!");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
So, when I compile and run this code through Netbeans (the postgresql.jar was included using GUI into Libraries folder) everything goes OK, the output is
Hello, sir!
Done, sir!
Opened database successfully
But when I try to run the compiled class file from cmd I get an error.
I placed Baseloader.class and postgresql42.jar into the same folder and cd'ed into that folder in cmd. Then I use the java -classpath postgresql42.jar Baserunner command which was proposed on one of the answers here, but it gava me Could not find or load main class Baseloader error.
If I type just java Baseloader it gives Exception in thread "main" java.lang.UnsupportedClassVersionError.
What I'm doing wrong and how to fix it?
EDIT: I've changed the java version in cmd: now java -version gives 1.8.0_73'.Then I checked which version Netbeans used: System.out.println(System.getProperty("java.version")) it also gave 1.8.0_73.
In environmental variables the JAVA_HOME is C:\Program Files\Java\jdk1.8.0_73, while System.out.println(System.getProperty("java.home")) gives C:\Program Files\Java\jdk1.8.0_73\jre. Can that difference be the case?
EDIT2: Changed JAVA_HOME to C:\Program Files\Java\jdk1.8.0_73\jre with no result.
Also javac -version gives the same newest 1.8.0_73 now.

Classpath for MySQL connector to JDBC-can't load the driver

I was trying to connect to MySQL using JDBC API. I have downloaded the MySQL driver which is the "mysql-connector-java-5.1.28-bin jar" file. My OS is Windows 7 and I have set the Classpath of Java to following path:
"E:\Myclass"
I have copied the above jar file to this folder.
Then I have written the following code to test if I can load the driver.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
System.out.println("Unable to load Driver Class");
return;
}
}
}
I expect everything should be working fine but I always get the "Unable to load Driver Class". Can anyone point out where was wrong? Thanks
Note: Thanks for all your answers. I have solved the problem. Since I am using Eclipse, I have add the JAR file to the classpath of the Eclipse.
You have to include the JAR in your classpath:
java -jar yourdriver.jar LoadDriver
JARs are filesystems. They should be added to your classpath the same way you add directories. Only classes will be loaded from the classpath you specified.
Use the below cmd to run it
java -cp E:\Myclass\mysql-connector-java-5.1.28-bin.jar; LoadDriver
As mentioned the mysql jar exist # E:\Myclass\mysql-connector-java-5.1.28-bin.jar , just set in the classpath and run it

JDBC connection works in IDE (eclipse), but not in .jar file

I'm really looking at a mystery here. I created a Java program in Eclipse and established a JDBC connection. The code is the following:
import java.sql.*;
public class Login {
public static void main(String[] args) {
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager
.getConnection("jdbc:sqlserver://localhost;databaseName=testdb; integratedSecurity=true;");
//adding port 1433 doesn't make a difference
System.out.println("Connection successful");
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("select * from testtable");
while (rs.next()) {
line = rs.getString(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I'm running it within eclipse, everything's fine. The database and tables are good, library and authentication in the Java Built Path are set and I get the result I want, namely "Hello World", which is a string in the selected table.
But creating an executable JAR file and running it throws the exception "This driver is not configured for integrated authentication". It does not even connect, so even if there was an error in the database it wouldn't matter at this point.
Even more confusing is the fact, that some weeks earlier, I also created an executable JAR file and it worked!
OS: Windows Vista Home Premium x86
JDBC driver location: "C:\sqljdbc_4.0\enu\sqljdbc4.jar"
Native library location: "C:\sqljdbc_4.0\enu\auth\x86"
Java version: Java 7 Update 17 and JDK 7 Update 17
Previousely, I used Update 21, but I changed back to check if the driver could be the reason.
So, any suggestions? I'd be very grateful!
Check the runtime classpath of eclipse, then try to create a system level "CLASSPATH" variable and add the same path. Once the variable is set, execute it in new command prompt or reload the environment variables
Make sure your executable jar has the dependency in MANIFEST.MF for all the necessary jars (along with MainClass)
Finally, It is always a practice in Java to make the first alphabet in Capital ("Login" instead of "login")
Actual problem is that if you run your project from eclipse, it will automatically add run arguments that are defined in run/run config//arguments, so you run your program with properly set path to sqljdbc_auth.dll. But if you export your application to .jar file and just run it, you will get these errors cause there is no correct classpath to auth file.
So, if you run your app from command line with proper arguments, it should be working.

package oracle.jdbc.driver does not exist

Error in the following code ![error occured][1]
import java.sql.*;
public class DBConnect{
public static void main(String a[]) throws SQLException{
// *package oracle.jdbc.driver does not exist*
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
System.out.println("Driver is registered");
}
}
You have to add ocjdbc jar in to your class path and try it like this.
if your jar file and java source is in same location. Use a command prompt and changed directory to that location. and execute following
javac -classpath ocjdbc14.jar DBConnect.java
and see.
import java.sql.*;
import oracle.jdbc.driver.OracleDriver;
public class DBConnect{
public static void main(String a[]) {
try{
Driver d=new OracleDriver();
DriverManager.registerDriver(d);
System.out.println("Driver is registered");
}catch(SQLException e){
System.out.println("Error occured "+e.getMessage());
}
}
}
You need to Add an oracle driver jar to the project build path,
Download Ojdbc14.jar file and put it in your classpath.
You need to do following steps if you are using intellij
Download jdbc7 or any version
Add this jar on following path File>>Project Structure>>Libraries>>
Image 1
Click on Modules and add jar there too
if you still face issue then you must see following problem
Image 2
Now click on problems>>fix>>add to dependency as given below
Image 3
Hope this will fix your issue
First run the program in netbeans and add Ojdbc14.jar file into the library of the program and then it will surely execute.
After executing in NetBeans, click Clean & Build Project.... This will create a jar file and then path like
java -jar "C:\Users\s\Documents\NetBeansProjects\jdbcTest_course\dist\jdbcTest_course.jar" will be provided.
Enter this into a command prompt (cmd) and it will run.

Categories