ClassNotFoundException in mvc application - java

I am getting ClassNotFoundException in this code when I run it on a server But as a stand alone java file it runs fine.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import UserJavaBean.UserJavaBean;
public class UserDataBase {
public int insert()
{
int flag =0;
try
{
UserJavaBean user= new UserJavaBean();
//Statement stmt= null;
PreparedStatement ps= null;
//ResultSet rs= null;
Connection conn;
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Class Loaded");
conn= DriverManager.getConnection("jdbc:oracle:thin:#localhost:****:orcl","hr","hr");
System.out.println("Connection Established");
// stmt= conn.createStatement();
int emp_id= user.getId();
String emp_name=user.getName();
String emp_des=user.getDesignation();
ps = conn.prepareStatement("insert into nanda values(?,?,?)" );
ps.setString(1,emp_name);
ps.setInt(2,emp_id);
ps.setString(3,emp_des);
ps.executeUpdate();
flag=1;
}
catch(Exception e)
{
e.printStackTrace();
flag=0;
}
System.out.println("flagvalue"+flag);
return flag;
}
}

You have not provided exception stacktrace. But I think you should provide the respective jar file of oracle.jdbc.driver.OracleDriver in class path as well as inside lib folder. You might have forget to provide the jar file inside lib folder of the project. As you are not getting any error during stand alone run, you have provide the jar file in class path and it is taking the class path jar file. But when you deploy your web application you have to provide the same jar file inside the lib folder. So that after deployment it will take the jar file from lib folder.
In a nutshell, After deployment, the class path jar files are not available for web app.
I think this will resolve your problem. Try it and let me know.

Related

JDBC JAVA No suitable driver found for jdbc:mysql://localhost:3306/voting

Hello im trying to connect to a mysql database using JDBC my code is below.I get an error as such No suitable driver found.Searching around I found that the usual error is syntax or missing the jar file from the class path.I tried both of these solutions and dont know what to do next it wont connect.Also to manage the databases I have WAMP and mySQL workbench installed not sure if its related.
package test.jdbc;
import java.sql.*;
public class jdbctester {
public static void main(String[] args)
{
try
{
Connection myconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/voting","root","Vanquish123");
Statement myStmt=myconn.createStatement();
ResultSet myRs=myStmt.executeQuery("select * from electoral");
/*
while(myRs.next())
{
System.out.println(myRs.getString("state")+","+myRs.getString("perDem"));
}
*/
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
Try this:
Class.forName("fully qualified driver class name");
Java Class.forName, JDBC connection loading driver
this post states that you should not need it but it will not hurt you to try.
you have to add "com.mysql.jdbc_5.1.5.jar" in to your project build path... go to project property>build Path> library> add external jar and add jar file.
Connection conn = null;
try {
// Register JDBC driver
Class.forName(DRIVER).newInstance();
// Open a connection
conn = DriverManager.getConnection(Local_URL + , USERNAME, PASSWORD);
System.out.println("Connected Database Successfully...\n\n");
} catch (Exception se) {
throw new AppException("Failed to create Local Database connection", se);
}
return conn;

Install Mysql driver on EC2 instance?

I have a Unix Instance ready on Amazon EC2 .I have installed mysql in it which is runnig on 3306 port. ( Note: It is not rds database from AWS)
I have created EmpDB databse in Mysql and have created Employee table. And I have written a java program to insert a row in Table.
Below is the code:
import java.sql.*;
import java.util.Calendar;
public class Test{
public static void main(String[] args) {
try{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/TaskDB";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "root");
String query = " insert into employee (id,name,dept,salary)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, 600);
preparedStmt.setString (2, "Rubble");
preparedStmt.setString(3, "startDate");
preparedStmt.setInt(4, 5000);
preparedStmt.execute();
conn.close();
} catch (Exception e){
System.err.println("Got an exception!");
e.printStackTrace();
}
}
When I am executing it via "java Test", getting below error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:359)
at java.net.URLClassLoader$1.run(URLClassLoader.java:348)
at java.security.AccessController.doPrivileged(Native Method)
at java.net
How I can install mysql connector on my Unix Instance?
Just copy the MySql-Connector.jar into Tomcat's lib folder, and then remove the jar from the webapp's lib folder, and then, re run the project.
import com.mysql.jdbc.Driver;
Put the driver in the same folder as my Test.java file, and compile it, resulting in Test.class.
So in this folder have
Test.class
mysql-connector-java-5.1.14-bin.jar
and I write this:
java -cp .;mysql-connector-java-5.1.14-bin.jar Test
This way if you not use any IDE just cmd in windows or shell in linux.

Connecting to MySQL using JDBC [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
I have searched the internet trying to find solutions on using java and JDBC to connect to MySQL. Unfortunately I have found multiple answers and none that solved my problem.
I downloaded the JDBC from MySQL, and unzipped the file to find the .jar. I placed the .jar in my C:/Program Files (X86)/Java/JDK.../JRE/lib/ext folder. I set my environmental variable classpath (maybe CLASSPATH, ClassPath ??) to the following:
%CLASSPATH%;.;C:\Program Files (x86)\Java\jdk1.8.0_65\jre\lib\ext
I use the script I composed based on all the different solutions I have seen to get this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySql {
public static void main(String[] args)
{
Connection con = getConnection();
if (con != null) {
System.out.println("Connection Made");
}
else {
System.out.println("Connection not made");
}
}
private static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "java", "java");
System.out.println("Connection Made");
conn.close();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
}
It compiles with javac MySql.java. Then when it runs (java MySql) I get com.mysql.jdbc. I have read that I don't need to register the driver, but when I remove Class.forName all I get is 'cannot find JDBC driver' error.
I can't narrow down my problem to either:
1). Classpath not setup correctly.
2). Improper java connection code.
3). Unable to locate MySQL server.
Any help would be appreciated.
Edit -
I placed the .jar file onto Desktop for testing purposes. Changed system classpath variable:
%CLASSPATH%;.;C:\User\User\Desktop\mysql-connector-java-5.1.38-bin.jar
Then when I add the trace for the error statement I get:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass<Unkown Source>
at java.lang.ClassLoader.loadclass (Unknown source)
at sun.misc.Launcher$AppClassLoader.loadclass(Unkown Source)
etc.
etc.
edit 2 - I have spent two days using Connect Java to a MySQL database as a resource and none of the instructions I have followed have solved my problem.
Instead of
System.out.println(e.getMessage());
Do this
e.printStackTrace();
You will see that the exception is:
java.lang.ClassNotFoundException: com.mysql.jdbc
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at MySql.getConnection(MySql.java:24)
at MySql.main(MySql.java:10)
Remove the Class.forName. You might get an access denied or some other error but it will solve the ClassNotFoundException. Here is the final edited version that should work:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySql {
public static void main(String[] args)
{
Connection con = getConnection();
if (con != null) {
System.out.println("Connection Made");
}
else {
System.out.println("Connection not made");
}
}
private static Connection getConnection() {
Connection con = null;
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila", "java", "java");
System.out.println("Connection Made");
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(0);
}
return con;
}
}
If you need Class.forName() you have to use correct class:
Class.forName("com.mysql.jdbc.Driver");
But with JDBC 4 that has become no longer needed.
Create full Exception stack traces and use the result to search here - most common errors have been solved here before.
NoSuitableDriverFound is a very strong indication your mysql-connector.jar (not the .zip....) is missing from your classpath when you run your code.
You could try like this:
Run java -cp .;C:\User\User\Desktop\mysql-connector-java-5.1.38-bin.jar MySql
I think you must add the path including the jar file name of the driver in your classpath. Like so:
%CLASSPATH%;.;C:\Program Files (x86)\Java\jdk1.8.0_65\jre\lib\ext\mysql-connector-java-xxx.jar
If your Java is version 6 or above you doesn't need Class.formName(...) code.
And for ensure that everything works, compile and execute your code in the follow way.
To compile:
java -cp PATH_TO_DRIVER; YOUR_CLASS.java
To execute:
java -cp PATH_TO_DRIVER; YOUR_CLASS
Change YOUR_CLASS to the name of your class and PATH_TO_DRIVER to the path where you download the MySQL driver.
Hope it helps!
Try this code!
public static void main(String[] argv) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/yourSCHEMAname,"login", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}

How to connect to mysql database using java?

I am trying to connect to mysql database and that is not done still because of the error,My code is as follows:
public static void main(String[] args) {
try{
String url = "jdbc.mysql://localhost:3306/db";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,"root","root");
Statement stmt = conn.createStatement();
String query = "insert into student values(1,abs)";
stmt.executeQuery(query);
System.out.println("Success...");
conn.close();
}catch(Exception e){
e.printStackTrace();
}
And the error is as follows:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Java_Database.main(Java_Database.java:11)
So anyone know well please help me.
1: download that msi you referred to # http://dev.mysql.com/downloads/connector/j/
2: run it. after it runs the install app vanishes, not exactly a roadmap for success for an install routine
from the root of c:\ I issue: dir mysql-connector-java-5.1.36-bin.jar /s
I let it run the whole way thru to confirm I didn't already have it installed elsewhere
C:\>dir mysql-connector-java-5.1.36-bin.jar /s
Directory of C:\Program Files (x86)\MySQL\MySQL Connector J
06/19/2015 09:26 PM 972,009 mysql-connector-java-5.1.36-bin.jar
1 File(s) 972,009 bytes
Total Files Listed:
1 File(s) 972,009 bytes
Seems consistent with my 5.1.35 filesize I was using before stumbling into your question
Btw, the above MySql Connect J folder date was just created so I am sure that was from the install
I copy (not moving it) it to my c:\javadeps folder.
I have a database called so_gibberish, and a table called thingws with 3 rows in it
source code (myTest.java):
I poached this stub off the internet as I am mostly a scala/jvm programmer. So please forgive. But it works.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class myTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/so_gibberish"; // **** MODIFY db name # end
String user = "stan"; // **** MODIFY
String password = "stan_password"; // **** MODIFY
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
System.out.println("------------------------------");
rs = st.executeQuery("select version()");
if (rs.next()) {
System.out.println(rs.getString(1));
System.out.println("------------------------------");
}
rs = st.executeQuery("select id,myCode from thingws");
while (rs.next()) {
System.out.println(rs.getInt(1)+": "+rs.getString(2));
}
System.out.println("------------------------------");
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(myTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(myTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
I will save it in C:\dev\java8\quick_java_mysql_test
compile and run (when you run it, it does a query for the mysql version, then a query on that table getting 3 rows)
c:\dev\java8\quick_java_mysql_test>javac myTest.java
c:\dev\java8\quick_java_mysql_test>java -cp .;c:\javadeps\mysql-connector-java-5.1.36-bin.jar myTest
output is:
------------------------------
5.6.24-log
------------------------------
1: C938CA
2: XYZ123
3: XYZPDQ
------------------------------
It is common to have a dependencies folder for jars at the project-level, such as a dep directory under the project folder.
Though I have that same jar file in it, it is not referenced, as seen in the -cp directive in step 7
that picks the jar up in c:\javadeps
plan your strategy according, and good luck
The mysql driver jar is not in the classpath.
Download it and copy it to a location visible from the classpath.
Here the link to the official driver.
You are using JDBC driver/connector for MySQL in your code.
You may download from below mentioned link.
https://www.mysql.com/products/connector/

Error: Could not find or load main class JDBCExample

Hello I am trying to run a java file in cmd (Windows) with this:
C:\test>java -cp c:\test\postgresql-9.3-1102.jdbc41.jar;c:\test JDBCExample
where postgresql-9.3-1102.jdbc41.jar & JDBCExample are already in the folder "test".
and JDBCExample.java is:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] args) {
System.out.println("-------- PostgreSQL "
+ "JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/testdb", "java_postgres",
"4scoreand7yearsago");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I have tried to run a simple "Hello World" java file in the same "test" folder yet it also says the same error.
And next, I also tried changing directory to a source folder of a .java file which I am REALLY SURE that it works perfect in Netbeans or Eclipse, (sorting algo and etc), yet still in the cmd it says the same error when compiling. :(
Any help? Also, I already added in the Path of my computer's Environment Variables a "C:\Program Files\Java\jdk1.7.0_45\bin;" and added a new one named CLASSPATH where it points to a "C:\Program Files\Java\jdk1.7.0_45\bin;C:\Program Files\Java\jre7\bin" but to no avail, still the same error.
OR COULD ANY OF YOU JUST HELP ME FIND ANOTHER WAY OF SETTING UP THE JDBC DRIVE. THAT'S ALL THANK YOU. T_T
My bad, it's only a matter of compilation and running problem.
/> javac JDBCExample.java
/> java JBDCExample
Sorry for the disturbance people! xD

Categories

Resources