Trying to Execute this java file from command line without using Maven etc to connect to Mysql with jar files placed at a $HOME/Dependancy/*.jar
import java.sql.*;
public class MysqlCon
{
public static void main(String[] args)
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bpx","romeo","BPXmysql*123");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select name from product_tbl");
while(rs.next())
System.out.println(rs.getString(1)+" Get Product ");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
still getting this error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
tried to get refer previous answers in the similar context ,but all of them refer of adding jar files and add them to the class path while executing which I have already done
Not sure what I am doing wrong
jar files used
mysql-5.1.10.jar mysql-connector-java-5.1.13.jar mysql-connector-java-8.0.26.jar
Thanks in Advance
cmd line code
javac -cp '.:/home/blesson/scripts/utilities/core_java/Dependancy/' /home/blesson/scripts/utilities/core_java/MysqlCon.java
java -cp '.:/home/blesson/scripts/utilities/core_java/Dependancy/' /home/blesson/scripts/utilities/core_java/MysqlCon
place mysql-connector-java-8.0.26.jar same folder where your .java file exist
open command line in the same folder or change directory to where your .java file exist
compile
javac -cp .:/home/sts0020/Desktop/java/jdbc/mysql-connector-java-8.0.26.jar YOUR_CLASS_NAME.java
run
java -cp .:/home/sts0020/Desktop/java/jdbc/mysql-connector-java-8.0.26.jar YOUR_CLASS_NAME.java
I'm trying to connect to my embedded H2 database via Java. I found various threads and tutorials on this and now have this code:
Connection con = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "username");
connectionProps.put("password", "password");
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:h2:~/test", connectionProps);
I got the "no suitable driver found for jdbc:h2:~/test" error message. I found the Class.forName(...) in some threads as a solution to this, but it doesn't seem to be working (ClassNotFoundException).
I read that the driver is probably not in my classpath, but don't really know what I need to do with that information. In the database view of IntelliJ the driver seems to work just fine (I can click reload drivers and it confirms the h2 driver). What am I doing wrong?
There are a couple ways to add to the classpath. I recommend trying to understand this page https://howtodoinjava.com/java/basics/java-classpath/ for more information on different strategies that have similar, but different results.
Probably the simplest way for just this project, would be to edit the "run configuration" that you are using, and add a new VM option:
–classpath /path/to/local/h2/driver.jar
Use an absolute path to the jar, and this will allow it to be present in the classpath when running it this way. In the link I shared, this is the same as adding the command line argument to the java or javac command, so this argument will work outside of intellij on the command line as well.
Edit:
Based on the comments, it seems like you might be using the %PROGRAMFILES% environment variable, with a fully qualified path.
Try this instead:
-classpath %PROGRAMFILES%\H2\bin\h2-1.4.200.jar
If you were to run the following command in your command prompt
echo %PROGRAMFILES%
I suspect you'd get the response:
C:\Program Files
Which is not the x86 version. So. Either use the environment variable and omit the part of the path it's value represents (eliminating the C:\ part)
or, if that's not the correct Program Files folder at all, then avoid it and try (note the quotes which are required because a folder has spaces in it's name):
--classpath "C:\Program Files (x86)\H2\bin\h2-1.4.200.jar"
Below approach I tried to run and compil
for compile:
javac -cp "C:\Program Files\Java\jdk1.7.0_45\bin;D:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc.jar" OracleTest.java
for execution:
java -cp "C:\Program Files\Java\jdk1.7.0_45\bin;D:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc.jar;." OracleTest
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
The JDBC drivers from oracle usually include a (Java) version number in the name like ojdbc14.jar or ojdbc7.jar. I do not have Oracle installed here, so please check the correct name in your directory D:\oracle\product\10.2.0\db_1\jdbc\lib\.
You can test my DBTester program I wrote a long time ago from here. After downloading the jar - eventually you need to rename DBTester.jar.zip to DBTester.jar - just execute it in the directory you saved the jar:
java -cp "DBTester.jar;D:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc7.jar" cfh.dbtester.Main -d
(assuming the ojdbc7.jar is the driver file and using Java 7 or later)
This should print a summary for some drivers, including the Oracle one, like
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
...
java.lang.ClassNotFoundException: com.ingres.jdbc.IngresDriver
oracle.jdbc.driver.OracleDriver OK
the last line is telling me that I have the OracleDriver available.
Note: DBTester.jar creates a file named dbtester.log with its results.
Can you try with this?
"%JAVA_HOME%\bin\java.exe" -cp "%~dp0\ojdbc.jar" OracleTest.java
Important thing to note here is to have the JAR file at the same location as of your JAVA class that you want to compile/execute and accordingly change the command.
Hope this helps!
This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 7 years ago.
I am having trouble compiling and running my Java code, intended to allow me to interface Java with a shared object for Vensim, a simulation modeling package.
The following code compiles without error:
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
However, when I try to run the following:
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
I get the following error: "Error: Could not find or load main class SpatialModel
". My SpatialModel.java code does contain a 'main' method (below), so I'm not sure what the problem is - can anyone please help me out? Thanks.
import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
public class SpatialModel {
private VensimHelper vh;
public static final String DLL_LIBNAME_PARAM = "vensim_lib_nam";
public static final String MODEL_PATH_PARAM = "vensim_model_path";
private final static int VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT = 10;
public SpatialModel() throws SpatialException {
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if(libName == null || libName.trim().equals("")) {
log.error("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
throw new SpatialException("Vensim library name has to be set with -D" + DLL_LIBNAME_PARAM);
}
if(modelPath == null || modelPath.trim().equals("")) {
log.error("Model path has to set with -D" + MODEL_PATH_PARAM);
throw new SpatialException("Model path ahs to be set with -D" + MODEL_PATH_PARAM);
}
for (int i = 0; i < VENSIM_CONTEXT_CREATION_MAX_FAILURE_COUNT && vh == null; i++) {
try {
log.info("creating new vensim helper\n\tdll lib: " + libName + "\n\tmodel path: " + modelPath);
vh = new VensimHelper(libName, modelPath);
} catch (Throwable e) {
log.error("An exception was thrown when initializing Vensim, try: " + i, e);
}
}
if (vh == null) {
throw new SpatialException("Can't initialize Vensim");
}
}
public static void main(String[] args) throws VensimException {
long before = System.currentTimeMillis();
String libName = System.getProperty(DLL_LIBNAME_PARAM);
String modelPath = System.getProperty(MODEL_PATH_PARAM);
if (libName == null) {
libName = "libvensim";
}
if(modelPath == null) {
modelPath = "~/BassModel.vmf";
}
System.setProperty(DLL_LIBNAME_PARAM, libName);
System.setProperty(MODEL_PATH_PARAM, modelPath);
if (args.length > 0 && args[0].equals("info")) {
System.out.println(new VensimHelper(libName, modelPath).getVensimInfo());
} else if (args.length > 0 && args[0].equals("vars")) {
VensimHelper helper = new VensimHelper(libName, modelPath);
String[] vars = helper.getVariables();
for (String var : vars) {
System.out.println(helper.getVariableInfo(var));
}
} else {
File f = new File(".");
System.out.println(f.getAbsolutePath());
SpatialModel sm = new SpatialModel();
}
System.out.println("Execution time: " + (System.currentTimeMillis() - before));
}
}
You must ensure that you add the location of your .class file to your classpath. So, if its in the current folder, add . to your classpath.
Note that the Windows classpath separator is a semi-colon, i.e. a ;.
If the class is in a package
package thepackagename;
public class TheClassName {
public static final void main(String[] cmd_lineParams) {
System.out.println("Hello World!");
}
}
Then calling:
java -classpath . TheClassName
results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:
java -classpath . thepackagename.TheClassName
And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.
To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.
Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”
You can try these two when you are getting the error: 'could not find or load main class'
If your class file is saved in following directory with HelloWorld program name
d:\sample
java -cp d:\sample HelloWorld
java -cp . HelloWorld
I believe you need to add the current directory to the Java classpath
java -cp .:./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
You have to include classpath to your javac and java commands
javac -cp . PackageName/*.java
java -cp . PackageName/ClassName_Having_main
suppose you have the following
Package Named: com.test
Class Name: Hello (Having main)
file is located inside "src/com/test/Hello.java"
from outside directory:
$ cd src
$ javac -cp . com/test/*.java
$ java -cp . com/test/Hello
In windows the same thing will be working too, I already tried
If you work in Eclipse, just make a cleanup (project\clean.. clean all projects) of the project.
You have to set the classpath if you get the error:
Could not find or load main class XYZ
For example:
E:\>set path="c:\programfiles\Java\jdk1.7.0_17\bin"
E:\>set classpath=%classpath%;.;
E:\>javac XYZ.java
E:\>java XYZ
I got this error because I was trying to run
javac HelloWorld.java && java HelloWorld.class
when I should have removed .class:
javac HelloWorld.java && java HelloWorld
Check your BuildPath, it could be that you are referencing a library that does not exist anymore.
If you're getting this error and you are using Maven to build your Jars, then there is a good chance that you simply do not have your Java classes in src/main/java/.
In my case I created my project in Eclipse which defaults to src (rather than src/main/java/.
So I ended up with something like mypackage.morepackage.myclass and a directory structure looking like src/mypackage/morepackage/myclass, which inherently has nothing wrong. But when you run mvn clean install it will look for src/main/java/mypackage/morepackage/myclass. It will not find the class but it won't error either. So it will successfully build and you when you run your outputted Jar the result is:
Error: Could not find or load main class mypackage.morepackage.myclass
Because it simply never included your class in the packaged Jar.
I know this question was tagged with linux, but on windows, you might need to separate your cp args with a ; instead of a :.
java -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar;./vensim.jar SpatialModel vars
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
If you try to run a java application which needs JDK 1.6 and you are trying to run on JDK 1.4, you will come across this error. In general, trying to run a Java application on old JRE may fail. Try installing new JRE/JDK.
Problem is not about your main function. Check out for
javac -d . -cp ./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel.java VensimHelper.java VensimException.java VensimContextRepository.java
output and run it.
Project > Clean and then make sure BuildPath > Libraries has the correct Library.
java -verbose:class HelloWorld might help you understand which classes are being loaded.
Also, as mentioned before, remember to call the full qualified name (i.e. include package).
I was using Java 1.8, and this error suddenly occurred when I pressed "Build and clean" in NetBeans. I switched for a brief moment to 1.7 again, clicked OK, re-opened properties and switched back to 1.8, and everything worked perfectly.
I hope I can help someone out with this, as these errors can be quite time-consuming.
This problem occurred for me when I imported an existing project into eclipse. What happens is it copied all the files not in the package, but outside the package. Hence, when I tried run > run configurations, it couldn't find the main method because it was not in the package. All I did was copy the files into the package and Eclipse was then able to detect the main method. So ultimately make sure that Eclipse can find your main method, by making sure that your java files are in the right package.
If so simple than many people think, me included :)
cd to Project Folder/src/package there you should see yourClass.java then run javac yourClass.java which will create yourClass.class then cd out of the src folder and into the build folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows
If you are using Eclipse... I renamed my main class file and got that error. I went to "Run As" configurator and under the class path for that project, it had listed both files in the class path. I removed old class that I renamed and left the class that had the new name and it compiled and ran just fine.
This solved the issue for me today:
cd /path/to/project
cd build
rm -r classes
Then clean&build it and run the individual files you need.
I have a similar problem in Windows, it's related to the classpath. From the command line, navigate until the directory where it's located your Java file (*.java and *.class), then try again with your commands.
I use Anypoint Studio (an Eclipse based IDE). In my case everything worked well, until I found out that while running the java code, something totally different is executed. Then I have deleted the .class files. After this point I got the error message from this question's title. Cleaning the project didn't solve the problem.
After restarting the IDE everything worked well again.
This question already has answers here:
SQLException: No suitable driver found for jdbc:derby://localhost:1527
(19 answers)
Closed 7 years ago.
I am trying to create a new SQL database with this Java program
import java.sql.*; //Needed for JDBC classes
public class BuildPhonebookDB {
public static void main(String[] args) throws Exception{
//Create a named constant for the URL
final String DB_URL = "jdbc:derby:Phonebook;create=true";
try {
//Create a connection to the database.
Connection conn = DriverManager.getConnection(DB_URL);
//Create a Statement object.
Statement stmt = conn.createStatement();
//Create the Entries table
stmt.execute("CREATE TABLE Entries (" +
"Name CHAR(20)"+
"Number INTEGER)"
);
System.out.println("Database Connected");
//Close the connection
conn.close();
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
When I try to run the program I get an error that:
No suitable driver found for jdbc:derby:Phonebook;create=true
I have looked at various other similar posts on Stack Overflow, such as this one, but none help. I have seen things about a driver jar, but I don't know what this is, if I need to edit this, could someone help me through it?
Thanks for any help
Did you see this guide and have you complited all step of this guide?
Apache Derby
Download Derby Download the binary Apache Derby distribution from the
Derby web site at http://db.apache.org/derby/derby_downloads.html.
These tutorial instructions use version 10.12.1.1 and assume you
downloaded one of the binary distribution files listed in the table
below:
Operating System Download File Windows db-derby-10.12.1.1-bin.zip
UNIX, Linux, and Mac db-derby-10.12.1.1-bin.tar.gz If a more recent
release is available, download that, then substitute that version
number for 10.12.1.1 in the following instructions.
Install Derby Choose the directory into which you want to install the
Derby software. You must have write permissions to this directory. The
sample instructions below use C:\Apache for Windows and /opt/Apache
for UNIX; be sure to use your actual location. Copy the software
distribution to the location you choose, then extract it as shown
below.
Windows (use your extraction tool e.g. WinZip -- these instructions
use mks unzip):
mkdir C:\Apache copy db-derby-10.12.1.1-bin.zip
> C:\Apache cd C:\Apache unzip db-derby-10.12.1.1-bin.zip
UNIX:
mkdir /opt/Apache cp db-derby-10.12.1.1-bin.tar.gz /opt/Apache
> cd /opt/Apache tar xzvf db-derby-10.12.1.1-bin.tar.gz
In both cases, the software will now be extracted into a subdirectory
named db-derby-10.12.1.1-bin.
Set DERBY_INSTALL Set the DERBY_INSTALL variable to the location where
you installed Derby. Examples are shown below, but be sure to use the
actual location on your system:
Windows: C:\> set DERBY_INSTALL=C:\Apache\db-derby-10.12.1.1-bin
UNIX Korn Shell:
$ export
> DERBY_INSTALL=/opt/Apache/db-derby-10.12.1.1-bin
Configure Embedded Derby To use Derby in its embedded mode set your
CLASSPATH to include the jar files listed below:
derby.jar: contains the Derby engine and the Derby Embedded JDBC
driver derbytools.jar: optional, provides the ij tool that is used by
a couple of sections in this tutorial You can set your CLASSPATH
explicitly with the command shown below:
Windows:
C:\> set
> CLASSPATH=%DERBY_INSTALL%\lib\derby.jar;%DERBY_INSTALL%\lib\derbytools.jar
;.
UNIX:
$ export
> CLASSPATH=$DERBY_INSTALL/lib/derby.jar:$DERBY_INSTALL/lib/derbytools.jar:.
...
Step 3: Embedded Derby
When an application accesses a Derby database using the Embedded Derby
JDBC driver, the Derby engine does not run in a separate process, and
there are no separate database processes to start up and shut down.
Instead, the Derby database engine runs inside the same Java Virtual
Machine (JVM) as the application. So, Derby becomes part of the
application just like any other jar file that the application uses.
Figure 1 depicts this embedded architecture.
Set the environment
To set up the environment, follow the "Configure Embedded Derby"
instructions.
Use this before you get the connection from the driver:
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();