Java insert image into database code not working - java

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

Related

How to fix java.sql.SQLException. No suitable driver for jdbc [duplicate]

This question already has answers here:
Getting the following error - No suitable driver found for jdbc:postgresql://localhost: 5432/testDBMS
(4 answers)
Closed 3 years ago.
I'm getting an error java.sql.SQLException No suitable driver for jdbc:derby:books when I try to run a file from command line. In Eclipse, everything works fine. I read a book "Java, How To Program" Deitel&Deitel and the file is an example from it. When I try to compile program from command line it shows no error, but the problem is with running. Please help
public class DisplayAuthors {
public static void main(String args[]) {
final String DATABASE_URL = "jdbc:derby:books";
final String SELECT_QUERY =
"SELECT authorID, firstName, lastName FROM authors";
String user="deitel";
String password="deitel";
try (
Connection connection = DriverManager.getConnection(
DATABASE_URL, user,password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.printf("Table Authors database books:%n%n");
for (int i = 1; i <= numberOfColumns; i++) {
System.out.printf("%-8s\t", metaData.getColumnName(i));
}
System.out.println();
while (resultSet.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
System.out.printf("%-8s\t", resultSet.getObject(i));
}
System.out.println();
}
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
Command line execution:
javac DisplayAuthors.java
java DisplayAuthors
You are running in the command line your class file without the dependencies.
In your eclipse IDE you maybe have a derby.jar or similar dependencies and eclipse adds all automatically to the execution. Is required to add all the dependencies when you are executing directly from the command line.
If you are note creating a runnable jar with dependencies in MANIFEST.MF and you are trying to execute the class directly is required to add the -cp parameter with the path to all the dependencies:
Example:
java -cp Derby.jar;. DisplayAuthors
Summing that the Derby.jar and your class are in the same place and there is no more dependencies to add.
More information about:
Java Command line (Oracle Java9 SE)
Differences between "java -cp" and "java -jar"?
java.sql.SQLException. No suitable driver for jdbc
The above error jumps when JDBC DriverManager can't find any suitable driver for the given connection URL. Either the JDBC driver isn't loaded at all before connecting the DB, or the connection URL is wrong.
The URL should be like this,
jdbc:derby://localhost:1527/dbname;create=true;
or
jdbc:derby:books;create=true;
Use create=true if you want the database to be created if it doesn't exist.
And finally, check that Derby JAR file is on the classpath. If you can't find it, then you can download the JAR from here and add to the project Library folder.
For Apache Derby, the driver class name is org.apache.derby.jdbc.ClientDriver. So put that as follows,
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection connection = DriverManager.getConnection(DATABASE_URL, user, password);
Make sure your URL, username and the password is correct, and try to run your code.

IntelliJ - Problem connecting to PostgreSQL

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.

Connector J installation

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)

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 .

Categories

Resources