Java: trivial setup, but can't resolve "ClassNotFoundException: org.postgresql.Driver" - java

On Mac, installed Java 12.0.2, postgresql-42.2.8.jar, PostgreSQL 11.5. From what I can tell, that version of the JDBC driver should be compatible with that version of PostgreSQL.
I've tried putting the PG jar file in my /Java/Extensions directory, and in the same directory as the following test program, and even set CLASSPATH to my test program directory, but I'm still getting ClassNotFound at runtime for the line Class.forName("org.postgresql.Driver"); in my test program:
import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC {
public static void main(String args[]) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/testdb",
"postgres", "123");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
The test program is taken directly from: https://www.tutorialspoint.com/postgresql/postgresql_java.htm
Any help/suggestions much appreciated... thanks.

Your classpath probably needs to explicitly reference the postgresql jar file. That's what I've always done. There might be some magic associated with putting jars in a particular directory, but I'm 99% sure that referencing a random directory in the classpath won't traverse .jar files, only .class files.

Related

Connect Java to MariaDB in VS Code

I need to connect to my database but I keep getting an error that says "driver not found".
I have added mariadb-java-client-3.0.8.jar jar file and it is still not working.
And this works pretty well on NetBeans, but I need to know how to fix that in VScode IDE. Do you know what I am missing?
import java.sql.Connection;
import java.sql.DriverManager;
public class App {
public static void main(String[] args) throws Exception {
try {
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/cpit305-project", "root", "");
System.out.println("working");
} catch (Exception e) {
System.err.println(e);
}
}
}
The exception:
java.sql.SQLException: No suitable driver found for jdbc:mariadb://localhost:3306/cpit305-project
First make sure your connection string is correct. Then the database name avoids the use of dashes (-).
The same code works fine for me.
Download the connection package here.
I have faced the same problem. I solved it by exporting classpath into my .zshrc file.
Add this to you shell:
export CLASSPATH=/path/mysql-connector-java-ver.jar:$CLASSPATH

No main class found

Language: Java
Program: Connecting to a database
Question: I'm trying to connect the sqlite database by following TutorialsPoint tutorial but I keep getting the main class not found error.
Implementation: My code is below followed by my terminal commands and folder structure screenshot. But basically all my files are located in one folder including the sqlite jar file.
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection c = null;
try{
Class.forName("com.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch(Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully!");
}
}
Terminal Commands
javac Test.java
java -classpath ".;sqlite-jdbc-3.23.1.jar" Test
Your problem was that you're explicitly trying to load the class com.sqlite.JDBC, whereas the driver class name must've changed somewhere along the way.
JDBC Type 4 drivers have added cleverness which allows you to specify only the connection URL, and the driver loads itself based on the beginning (i.e. jdbc:sqlite). No need to wonder what was the driver class's name.
Rant unrelated to the issue at hand:
Unfortunately people read old tutorials written by less than experts, so we constantly see Class.forName() being used, as well as the more serious issue, which is using Statement instead of PreparedStatement.
My classpath option was incorrect. I was on linux and was trying to do:
java -classpath ".;sqlite-jdbc-3.23.1.jar" Test
the correct way was
java -classpath ".:sqlite-jdbc-3.23.1.jar" Test
colon not semicolon. Unfortunately now it's giving me and error" ClassNotFoundException: com.sqlite.JDBC;
I will look into this.
Thanks for the comments which helped me find the error

JDBC cannot be resolved to a variable in Eclipse

Currently trying to use a sqlite-dbc4-3.8.2-SNAPSHOT.jar that was given to me as part of an assignment. I've tried running my main file and I get the errors below:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
org.sqlite.JDBC cannot be resolved to a variable
at DbBasic.open(DbBasic.java:54)
at DbBasic.<init>(DbBasic.java:67)
at DbUser.<init>(DbUser.java:40)
at Main.go(Main.java:12)
at Main.main(Main.java:65)
Here's part of the DbBasic class that attempts to connect and open a database using JDBC:
private Connection getConnection()
// get the connection
{
Connection con = null;
try {
con = DriverManager.getConnection(SQLITE_DATABASE_LOCATION+dbName);
con.setAutoCommit(false);
}
catch (SQLException sqle)
{
notify("Db.getConnection database location ["+SQLITE_DATABASE_LOCATION+"] db name["+dbName+"]", sqle);
};
return con;
} // end of method "getConnection"
private void open()
// "open" the database : actually really setting up the connection and obtaining the metadata about the server
// makes sure that database file is present before trying to establish connection
// otherwise SQLite will create a new, empty database with the name provided
{
File dbf = new File(dbName);
if (dbf.exists() == false)
{
System.out.println("SQLite database file ["+dbName+"] does not exist");
System.exit(0);
};
try {
Class.forName(org.sqlite.JDBC);
con = getConnection();
} catch ( ClassNotFoundException cnfe ) {
notify("Db.Open",cnfe);
};
if (debug) System.out.println("Db.Open : leaving");
} // end of constructor "Open"
I have already tried adding external JAR's and the .jar file is then added to my 'Referenced Libraries' in Eclipse.
I'm having trouble understanding the Class.forName(org.sqlite.JDBC) and how to make it work with my .jar file
Though the post is relatively old and the OP might not be interested in a solution for this issue now anymore, thought of putting this as an answer. It might help someone who runs into such silly issues. This is one of the common mistakes that people do while using Eclipse as an IDE, try to run code that doesn't even compile.
You can check the "Problems" view in Eclipse and fix the compilation errors and then try to compile your program. The obvious error here on this question is the missing double quotes "" while using the driver name.
Class.forName("org.sqlite.JDBC");

Getting Error when connection to MySQL database

I have downloaded the following:
mysql-essential-5.1.65-win32 from this MySQL Dev link
MySQL Connector mysql-connector-java-5.1.21.zip from this link
Now I have started programming with Eclipse. I have made simple java class like below,
public class MySQLAccess {
private static Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args){
try{
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
}catch (Exception e) {
// TODO: handle exception
System.out.println("Error : "+e);
}
}
}
I have also made a folder "lib" in my Java project and I have put that mysql-connector jar over there. But when I run this program it can't find mysql I get the following error in the console :
Erro : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Can someone please tell me where I have made the mistake? Thank you
Putting the full jar-file path in your classpath and restarting cmd (if you are running from cmd) should work-
See here- java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
If it your java application project then you put jar file into jdk library path ext folder.
eg:
C:\Program Files\Java\jdk1.6.0_13\jre\lib\ext
you will get path from your project class path .

oracle.jdbc.OracleDriver found in application, not in Test

When I connect to the OracleDriver in the application, everything is fine. But when I want to connect to run the JUnit Tests, I got a ClassNotFoundException. And I do exactly the same!
I have the ojbc added to the library and the testlibrary.
public JDBCDataStorage(boolean production) throws DataStorageException {
this.production = production;
try {
rb = (PropertyResourceBundle) PropertyResourceBundle.getBundle("app.control.database.JDBCconfig");
Class.forName(rb.getString("driver"));
} catch (ClassNotFoundException e) {
throw new DataStorageException("Something went wrong in new JDBCDataStorage()" + ": " + e.getMessage());
}
DriverManager.setLoginTimeout(3);
}
Check for two things
That rb.getString("driver") actually returns the FQCN of your driver.
That the driver JAR is in classpath of your test application
Try adding the Oracle JDBC driver jarfile to the classpath of the JUnit test. If you're running the unit test in Eclipse, add the driver jarfile to the User Entries in the Run Configuration of the JUnit test.

Categories

Resources