So I've looked up a lot of different videos / tutorials. I've read through the MySQL connector J installation guide.. and I am still super confused!
I used the MySQL Installer to install all of the MySQL products.
Here is a pic of the installation.
This displays that connector J is installed, and its current location.
So I read that I need to 'set the classpath' -- these words literally haunt me at night x_x.. but it seems like something that really shouldn't be difficult. I went to my environment variables and noticed right away that there is nothing there currently called CLASSPATH or classpath or Classpath.. you get it. It's not there. So I created one, but I am positive that it's not right, or that is not what my problem is. Heres a pic: pic of current classpath
I've seen in a lot of videos that they say I 'must' download different external tools to get it to work, but that doesn't make sense to me, and the MySQL installation guide doesn't ever mention that, plus those videos are all possibly out dated.
I attempted to run this code:
import java.sql.*;
public class Main {
private static String connectionString = "jdbc:mysql://localhost:3306/test";
private static Connection connection;
private static Statement command;
private static ResultSet data;
public static void main(String[] args) {
// launch(args);
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionString);
command = connection.createStatement();
command.execute("INSERT INTO accounts VALUES (default, 'test1', 'password1', 2018-12-18)");
} catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
System.out.println("cnfe was thrown");
}catch(SQLException sqlE) {
sqlE.printStackTrace();
}
}
}
That returned two separate errors:
1
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.tjp.Main.main(Main.java:31)
2 -- this one occurs without the "forName" method.
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.tjp.Main.main(Main.java:33)
Any help will be greatly appreciated!! Thank you so much
Visit :
How to Add JARs to Project Build Paths in Eclipse (Java)
Related
I am new to PostgreSQL (I normally use other database engines), and I also do not use Java often.
My Problem is that I get the following exception:
java.sql.SQLException: No suitable driver found for DATABASE_NAME
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
I followed this tutorial: http://www.postgresqltutorial.com/postgresql-jdbc/connecting-to-postgresql-database/ and added postgresql-42.2.5.jar as a library.
The problem is that adding the driver as a library, as can be seen in the screenshot, has no effect.
So my question is: how do I connect to a PostgreSQL database using Java and the latest IntelliJ?
Any help would be appreciated.
UPDATE 1:
UPDATE 2:
Since the code has been requested: I have replaced the original code by a minimal code that will cause the error:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class IngestData
{
protected static String url;
protected static final String user = "user";
protected static final String password = "password";
public static void main(String[] args)
{
Connection connection = null;
url = args[args.length-1];
try
{
connection = DriverManager.getConnection(url, user, password);
System.out.println("SUCCESS");
} catch (SQLException e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
The console output is:
ERROR
java.sql.SQLException: No suitable driver found for http://127.0.0.1:10282/db01617792
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at IngestData.main(IngestData.java:17)
Process finished with exit code 0
Here is the link to the git repository containing the code:
https://github.com/ka6555/StackOverflow-Postgresql-Problem.git
UPDATE 3:
I found the error:
I need to change
protected static String url;
to
protected static String url = "jdbc:postgresql://";
and
url = args[args.length-1];
to
url += args[args.length-1];
While this solves my original problem, the program is now stuck executing the following line:
connection = DriverManager.getConnection(url, user, password);
There is no error but the program will simply run like with an endless loop never going beyond this code line.
UPDATE 4:
I have fixed all problems now.
It seems like you are missing the postgres jar file in your project dependencies.
Open the Project Structure (Ctrl+Alt+Shift+S on Windows)
Select modules / dependencies tab
You should see something like the following:
If the postgres dependency is missing:
Klick on the + sign on the right side of the screenshot
Choose Library/Project Library and your postgres jar file
Your code should now run. Let me know if it helps.
Note: Please provide your minmal working code on GitHub for a quicker response.
The main problem was that I used a command line parameter as the database url without prefixing it with jdbc:postgresql://. Additionally, I had to reinstall postgresql because of some odd behavior I could not figure out the reason for.
This is the message you get when the URL syntax is incorrect.
This is the requirement.
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
As you can see that I am in the current path of executing the java file.
When I compile the program I am getting a class file successfully.
but wen I run it I m unable to execute that program as I am getting the error in the image telling that there's no such class in that path available..
C:\Users\admin>javac insertImg.java
C:\Users\admin>java insertImg
Exception in thread "main" java.lang.NoClassDefFoundError: insertImg
Caused by: java.lang.ClassNotFoundException: insertImg
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: insertImg. Program will exit.
C:\Users\admin>
And this is my java code for inserting image into database.....
insertImg.java:
import java.sql.*;
import java.io.*;
public class insertImg{
public static void main(String[] args) {
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "hibernatetutorial";
String userName = "root";
String password = "root";
Connection con = null;
try {
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
File imgfile = new File("images.jpg");
FileInputStream fin = new FileInputStream(imgfile);
PreparedStatement pre = con.prepareStatement("insert into Image values(?,?,?)");
pre.setInt(1,5);
pre.setString(2,"Durga");
pre.setBinaryStream(3,fin,(int)imgfile.length());
pre.executeUpdate();
System.out.println("Inserting Successfully!");
pre.close();
con.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Does insertImg.java have a class insertImg (note case sensitivity), that has a public main function?
I see You got the code from roseIndia it is working for me without any hitch. however its still weird from whatever your showing ..my suggestion is to use an IDE like eclipse
you can always try the following steps
1) Create a table in your Mysql database to suit the above code
CREATE TABLE IMAGE
(
IMG_ID INT,
IMG_NAME VARCHAR2(100),
IMG BLOB
)
2) Create a new java project in eclipse and create a new class insertImg and paste the code there. please make sure your image file path is same as where your image is and run it. Its working fine
Ive tried with Oracle database had to add the -classpath ojdbc.jar and it worked from the console also as you can see in the image
and my image file that i loaded in the database is in D:\ so its is not in the above screenshot
hope this helps
This is a simple classpath error. The CLASSPATH environment variable allows Java to know where to look for classes.
Unfortunately, Java is not intelligent enough to know that it needs to look for classes in the local directory. To resolve this issue, all you have to do is execute one of the following statements depending on whether you are using windows or Linux/Unix:
For Windows:
set CLASSPATH=.;%CLASSPATH%
For Linux:
export CLASSPATH=.:$CLASSPATH
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 .
I am on a Mac running Netbeans 6.9.
I downloaded and installed LWJGL using this tutorial down to the letter:
http://lwjgl.org/wiki/index.php?title=Setting_Up_LWJGL_with_NetBeans
I finished the installation and copied sample code to see if my system is working. I got a bug, and was not sure if it was because of faulty code or I was doing something wrong. So I shortened down the code to this little simple bit:
package javaopengl;
import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
//Testing
public class Main {
public static void main(String[] args) {
boolean fullscreen = (args.length == 1 && args[0].equals("-fullscreen"));
try {
Display.create();
Display.destroy();
} catch (Exception e) {
e.printStackTrace(System.err);
}
System.exit(0);
}
}
But I still get the same error:
run:
Exception in thread "main" java.lang.NoClassDefFoundError: =
Caused by: java.lang.ClassNotFoundException: =
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
I am not sure what exactly is going on, Would you please tell me what is going on and how to fix it?
Note: When i am looking at the text in the development environment, it does not show those red lines indicating there are any errors.
What are you typing (or what is netbeans running) to run this? Since the Mac filesystem is fairly case-agnostic unless you've specified otherwise, running java javaopengl.main will look for a file main.java, which is there (Main.java will be returned). But the class is Main, and you can get this exception from the difference. If this is being run from an ant script, I suggest making sure you have the correct capitalization (the class should be javaopengl.Main). A simple way to test this is to delete everything except the class definition and an empty public static void main(String[] args) {}
Alternatively, you could have something simpler, like your classpath out of whack. Missing the lwjgl jar would get you there, but if you followed the directions in that tutorial, that actually seems less likely. Still, you can test this.
package javaopengl;
public class Main {
public static void main(String[] args) {
System.out.println("well, main works");
Class checkjar = Class.forName("org.lwjgl.opengl.Display");
System.out.println("My ClassLoader found: " + checkjar.getCanonicalName());
}
}
Also, remove import org.lwjgl.Sys; from your shortened example. It doesn't appear to be needed, provided it isn't the source of your problems :).