I am having some difficulty in making connectivity with Java and PostgreSQL Database.I have download the JDBC4 Postgresql Driver, Version 9.2-1002 driver and properly set the application ClassPath. My code is as under
import java.sql.*;
public class JavaPostGreSQLConnectivity
{
public static void main(String[] args)
{
DB db = new DB();
db.dbConnect("jdbc:postgresql://127.0.0.1:5432/TestDB", "postgres","pwd");
}
}
class DB
{
public DB() {}
public void dbConnect(String db_connect_string, String db_userid, String db_password)
{
try
{
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
Upon running I am getting the below error
Is it complaining about
Class.forName("org.postgresql.Driver");
If so then what will be the driver name? However, I followed this for my learning purpose.
However, If I do
C:\Program Files (x86)\Java\jdk1.7.0\bin>java -cp C:\Users\pos
tgresql-9.2-1002.jdbc4.jar; JavaPostGreSQLConnectivity
connected
It works.Why I need to explicitly mention the driver again when I have already placed it in the classpath properly? Is there any alternative way (I just want to put the JAR file in Classpath and the program should read from there)?
Thanks in advance
The driver name is OK. It is the same as mentioned in the official docs of the driver. Therefore the driver is just not in the classpath.
You say:
I [...] properly set the application ClassPath
On the other hand you start the program by just calling:
java JavaPostGreSQLConnectivity
In that case no PG driver is on the classpath. You have to add it by hand using someting like
java -cp postgresql-jdbc4.jar JavaPostGreSQLConnectivity
EDIT The question has been changed while typing, hence the duplication.
You added the jar only in you IDE. This helps the IDE to compile your code. If you start the program using you IDE then the IDE will also set the classpath for you. But if you don't start via the IDE then nobody knows the correct classpath and it has to be set by hand.
Your options are:
start always via IDE
make some batch script which hides the setting of the classpath (common solution)
set the CLASSPATH environment variable (does not scale with other Java applications)
make an "Executable Jar" and set the classpath there. (Search this site using that term).
put the jar into a place where the JVM picks it up automatically (e.g. in the lib/ext directory of the JRE). But polluting the JRE/JDK libs is the worst option.
Note: This is all basic Java knowledge and has nothing to do with PostgreSQL.
Related
I have created a program that works perfectly in the IDE on NetBeans, but anytime I build the .jar file, the database connection stops working. I've already added the CLASSPATH to the MySQL Connector, as well as defined Class.forName("com.mysql.jdbc.Driver"); Still nothing..
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/gearheads";
Connection conn = DriverManager.getConnection(url,"root","HellOnEarth202021");
Statement stmt = conn.createStatement();
ResultSet rs;
String pid = txt_staffID.getText();
rs = stmt.executeQuery("SELECT name,timeraccess FROM staff WHERE staffid = '"+pid+"'");
while ( rs.next() ) {
String timeraccess = rs.getString("timeraccess");
String staffName = rs.getString("name");
getLogin = staffName;
System.out.println(staffName);
System.out.println("Users Admin Level: " + timeraccess);
if ( timeraccess.equals("1")) {
this.dispose();
new menu().setVisible(true);
System.out.println("Access Granted");
}else
System.out.println("Access Restricted.");
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
txt_staffID.setText(e.toString());
System.err.println(e.getMessage());
}
This, as it stands, outputs:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Where taking out the Class.forName outputs:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/gearheads
Please help me. This link is a screenshot of my libraries.
My Libraries:
If its runnning correctly inside Netbeans, then the MySQL driver is correct.
You have to search for Manifest file (MANIFEST.MF) and probably will have to unjar the contents of the driver inside your own JAR file.
I'll leave this answer by now, but will try to gather the details to bring it back here.
I also use NetBeans and when I generate the JAR file, its already copying the dependant libraries and generating the correct MANIFEST.MF.
I ended up with the following structure
MyProject\dist\lib\JdbcDriver.jar
and
MyProject\dist\MyProject.jar
Inside MyProject.jar, I have the following MANIFEST.MF:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.7
Created-By: 1.8.0_201-b09 (Oracle Corporation)
Class-Path: lib/JdbcDriver.jar
X-COMMENT: Main-Class will be added automatically by build
Main-Class: myproject.MyMainClass
Please, verify with you are copying the lib folder altogether with your JAR file.
Just to leave here the final solution (#Nick Media final comment): you have to check "Copy Dependent Libraries" in Build>Packaging Project Properties.
It is not clear exactly what you are doing wrong, but you are clearly doing something incorrectly:
It is often better to use DriverManager.getConnection rather than Class.forName and a specific driver class name. This is the approach recommended by the Oracle Java Tutorial; see https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
If you are loading the driver via its classname, use com.mysql.jdbc.Driver with MySQL Connector/J 5.x and com.mysql.cj.jdbc.Driver with MySQL Connector/J 8.x.
If this is a webapp, make sure that the relevant driver JAR file is actually in your WAR file, and/or that it is being deployed correctly.
If this is a command line app, make sure that you include the driver JAR on the runtime classpath. (Especially if you are trying to run it outside of your IDE.) Alternatively, consider creating a shaded JAR that included all of the apps dependencies. (It is a bit hard to advise since you haven't told us if you are using a build tool like Ant, Maven, Gradle, etc.)
The driver doesn't actually need to be a compile time dependency, though there is little harm in doing that. (The harm is that you might accidentally add imports to the MySQL implementation classes to your app ... and run into problems.)
Running into an issue with a JAVA application that I'm hoping someone can provide some clarity to. I have a simple Java Application which is being built in the Eclipse IDE. I have JRE 1.8.0_251 installed on PATH.
My application at a basic level performs the following:
Load a properties file
Connect to a MSSQL Database based on that SQL File (using java.sql.Connection)
Queries some data.
Updates some data.
This all works without issue in Eclipse. However, when I export my file to a runnable .JAR file, it appears to stop after attempting to initialize the database connection. However, it does not throw a SQLException and never returns from the method. I checked my .jar file in 7ZIP to make sure that the SQLJDBC42.jar was packaged in the folder and it was.
The last log line I see when my runnable JAR executes is: Log.info("Connecting to Database...") however, all items run / and are logged in Eclipse execution.
Any ideas? Code below:
public void ConnectDatabase() {
Log.info("Connecting to Database...");
try {
//Connect to Database and Log success.
ConnectionInstance = DriverManager.getConnection(connectionURL);
Log.info("Database Connection Successful.");
} catch (Exception e) {
Log.info(String.format("ERROR | DATABASE: %s", e));
//System.exit(0);
}
Log.info("Leaving Database Method.");
}
It's really weird, but please hear out the story.
We both know the behavior of DriverManager during connector registering. I swear it was worked as expected, then suddenly it started keep throwing SQLException: no suitable driver found. To fix it, I have to break the jar file and expose the content folders directly under the classpath with my bare hand.
I then concluded that something stopped my DriverManager from being able to open the jar file automatically. It looks like a weird access permission problem. My system is windows 8.1 and I run java under administrator:cmd.
import java.sql.*;
public class Test{
public static void main(String... args) throws Exception{
String url = "jdbc:mysql://localhost:3306/bobbooks";
Connection conn = DriverManager.getConnection(url, "root", "password");
}
}
I have few classpath folders, only one of them contains the jar file.
OK, here is the code below, just a simple test class
I really want to fix this problem nicely, without breaking the jar file. Somebody help pls
I wonder if I understood what I was learning, but here I got the solution:
Simply edit the environment variable, to add the jar file as a CLASSPATH, like this:
(CLASSPATH:)
D:\mysql-connector-java-5.1.35-bin.jar;
then it works just fine.
Hello guys I have create a small java application for desktop that simple logs data into an sqllite database. The jar files work well on the computer that was built, but, when I distributed on other pc it display the message that goes like this java.lang.ClassNotFoundException:org.sqlite.jdbc
I used this code: I know I have to change the classpath apparently, but I am not sure how to proceed so that this program work on other pcs. I notice that this programs works well on the pc that it was built on but it is because i used this classpath..."jdbc:sqlite:C:\Users\USUARIO\Documents\workspace\School2015.sqlite"... which is my local computer.
My question is how do I change this classpath so that the program runs fine on other pc than the one it was built on?
public class sqlConnection {
Connection conn=null;
public static Connection dbConnector()
{
try{
Class.forName("org.sqlite.JDBC");
Connection conn=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\USUARIO\\Documents\\workspace\\School2015.sqlite");
JOptionPane.showMessageDialog(null, "BIENVENIDO! Estás Conectado");
return conn;
}catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Not sure how you package and/or run this but if you place the School2015.sqlite file inside of the built JAR file you are creating and reference it from the relative path instead of the absolute one you will have no problems sharing the app.
You could look into using Maven as a build tool that will allow you to package everything up.
I am trying to have an OSGI bundle access a MYSQL DB, using Eclipse as my IDE (Windows 7 x64). I am able to load the jdbc connector. The actual .jar is placed in all \bin folders in the java install directories, along with the \bin folder of the bundle. I have set the environment classpath variable to this folder also. I have an error stating that the driver is not suitable. I know OSGI has some issues with drivers etc. Can someone recommend a way to circumvent this?
ClassLoader DBHCL = ClassLoader.getSystemClassLoader();
DBHCL.loadClass("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver", true, DBHCL).newInstance();
System.out.println("Class Loaded");
//DriverManager.getDriver("jdbc:mysql://localhost/timedb");
//System.out.println("Driver Gotten");
conn = DriverManager.getConnection(URL + DBName,username,password);
System.out.println("Connection Created");
stmt = conn.createStatement();
System.out.println("Statement Created");
connFlag = true;
Console Output, Error: osgi> start 7 Data Base Service (MYSQL) Starting Class Loaded No suitable driver found for jdbc:mysql://localhost/timedb Exception in thread "Thread-1" INSERT INTO appliance1...
Does anybody have any insight into this problem?
I have tried making a separate bundle solely for the jdbc driver and exporting/importing this to the appropriate bundle, but no luck.
Thanks
In your code snippet, you get the SystemClassLoader, and you ask it for the "com.mysql.jdbc.Driver". Given that that call doesn't give you a ClassNotFoundException, we can conclude the system classloader can find the class for you; the driver will then register itself to the DriverManager.
However, you don't see the same DriverManager that the MySQL driver does! The MySQL driver sees the one from the system classloader, but your code (conn = DriverManager. ...) uses the one from the bundle's own classloader. These are two different classes, hence, no suitable driver is found.
My solution would be to not use the SystemClassLoader (which you shouldn't do in OSGi anyway, unless you know exactly what you're doing), but use the bundle's classloader. So, I would
not put the MySQL jar on the system classpath, but let OSGi do the hard work. You can put the jar in a bundle, and put the jar on the Bundle-ClassPath. You can then choose either to keep it private to your bundle (if you're the only one using it), or export the packages.
In stead of using the system classloader, use the bundle's classloader. This can be as simple as using Class.forName("com.mysql.jdbc.Driver"); this will do the right thing.