Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver - java

I wanted to print the contents in a database but whenever I run this program I got this error saying that
Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I have installed MySQL from this link http://dev.mysql.com/downloads/windows/installer/ its a 248mb file and installed completely. I can access my database within MySQL but can't able to access from netbeans. I separately downloaded the mysql-connector-java-5.1.4.jar and set the CLASSPATH but now also I got this error.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydatabase","root",
"root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

First Check can you import import com.microsoft.sqlserver.jdbc.SQLServerDriver;
if it say com.microsft can not be resolved to a type that means u have to add your jar files to java build path and after that to deployment path from project properties.
java build path
Right click on project=>Properties=>Java Build Path=>
Librariess=>ADD External Jar file
deployment path
Right click on project=>Properties=>Deployment Assembly=>
ADDs=>Java Build Path Entries==> mssql_jdbc

The CLASSPATH environment variable is only used by the java.exe command and even then only when used without any of the -cp, -classpath, -jar arguments. It is ignored by IDEs.
So if you are running the application from your IDE place the mysql-connector.jar in your IDE's classpath

I downloaded the mysql-connector-java-5.1.4.jar file and placed in "C:\Program Files\MySQL\Java Connector" directory and edit System Environment Variable from control panel then set CLASSPATH as C:\Program Files\MySQL\Java Connector
Add the jar file, not the directory that the jar file is in.
Instead of,
C:\Program Files\MySQL\Java Connector
the CLASSPATH should include,
C:\Program Files\MySQL\Java Connector\mysql-connector-java-5.1.4.jar

Related

Why do I get java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver when mysql-connector-java-8.0.16.jar is in the classpath?

I get a java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver when I type this into the windows command line
javac src/*.java -d class -cp lib/*
java DBTest -cp lib/*
I have also tried using com.mysql.cj.jdbc without Driver at the end. I add newInstance() to line 11 so it was:
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
but there was no change.
I also tried it without Class.forName() since this is deprecated, but I got a java.sql.SQLException: No suitable driver found
mysql-connector-java-8.0.16.jar is the only file in lib. I have also tried putting it in in the folder where I run DBTest.java. I set the Classpath from the command line using
set CLASSPATH = .
and by creating the environment variable CLASSPATH through advanced system settings. I then tried compiling and running with and without -cp since it should be checking the current directory for the jar file.
I also tried to run this in eclipse, but eclipse crashed and will no longer open.
import java.sql.*;
public class DBTest{
public static void main(String args[]) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from employees Limit 10");
while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getDouble(3));
}
con.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The entire error message is
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
You have the arguments to java in the wrong order. Putting arguments after the classname will pass those arguments to the main method of your class, it won't set the classpath.
You need to put the arguments before the classname. Also -d class is not a valid argument for java. In short, you need to use:
java -cp class:lib/* DBTest

JDBC no suitable driver found just on Linux? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
I am trying to write a program to connect to a MySQL database in eclipse, but I get the error "java.sql.SQLException: No suitable driver found".
The java code is:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
The output in the console tab is:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
I have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.
Also refer to this image. There is an ! mark at the project root.image01
I get the error as in the next image: image02 when I include the 2 commented statements:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
For all but the most trivial applications the CLASSPATH environment variable is NOT used. Normally the libraries are include in the Class-Path entry in the manifest of the jar, or in the -cp option of the java commandline.
In this case you need to add the MySQL JDBC driver to the buildpath of your Eclipse project.
I had the same problem. I solved it by adding:
Class.forName("com.mysql.jdbc.Driver");
you can place the path like java -cppwd/mysql-connector-java-5.1.22-bin.jar:. <classname>.
make sure that your in same directory where the mysql driver is .
Hope that helps .
Load Driver class just before getting the connection.
Use this code:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "user", "passw");
Alternatively you can also add the installed jar file to your eclipse project by selecting the project in eclipse, right click it and go down to properties, select the Java Build Path>>select the Libraries Tab>>Add external jar file and browse for the installed mysql-connector-java.jar file or any mysql java connector file int the /usr/share/java/ directory for most ubuntu users. Click okay and rebuild your project. Good luck
I encountered the same problem as you, but I handled it as follows:
I copied the jar, which is called mysql-connector-java-5.1.23-bin.jar, into the \Apache Software Foundation\Tomcat 6.0\lib, and restarted tomcat.
Hope that helps

how to link java and mysql

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}
First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done
1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help

Java to Database Connection : Exception

I am connecting my java program to mysql database. But i get an exception block executed instead of getting connected i.e, "Connection Failed!!".
import java.sql.*;
public class Mysqltest
{
public static void main(String args[])
{
String username ="root";
String password ="bharath12";
String url ="jdbc:mysql://localhost:3307/";
String dbName = "sample";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try
{
Class.forName(driver).newInstance();
con=DriverManager.getConnection(url+dbName, username, password);
System.out.println("Connection successfully established.");
con.close();
System.out.println("Connection terminated !");
}
catch(Exception e)
{
System.out.println("Connection failed !!");
}
}
}
What would be the error in the above code?
I deliberately changed mysql port to 3307 during installation (hence, localhost:3307)
You should not have additional space only separator allowed is in classpath variable for windows is ;
So your CLASSPATH variable should be like below-
C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;C:\Program Files\Java\jdk1.7.0_07\lib\mysql-connector-java-5.1.22-bin.jar;
There is a space in your class path before mysql jar.
Moving ahead it is advisable to use class path with -cp option rather than global CLASSPATH since global class path has precedence over application class path it can create problems if there are same classe names in different jar which is mentioned in Global Classpath.
You can also start using editor like Eclipse in which you can simply add required jar files in build path.

Where do you put the Oracle's JDBC Thin Driver for Crystal Reports?

Where do you save the jdbc thin driver for Oracle? I have tried jre/lib/ext but my program, Crystal Reports keeps saying it can't find it. I figure I have saved it in the wrong place.
If I go to a command prompt and use:
C:\TEMP>java oracle.jdbc.OracleDriver
Oracle 11.2.0.3.0 JDBC 4.0 compiled with JDK6 on Fri_Aug_26_08:19:15_PDT_2011
Default Connection Properties Resource
Wed Oct 12 14:02:05 EDT 2011
So I know it is there.
edit: Since I could not get CR to work I tried a console app but it cannot find the driver:
package javaapplication1;
public class JavaApplication1 {
public static void main (String[] args) throws Exception
{
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:#myserver:1521:mysid", "myid", "mypass");
// #//machineName:port/SID, userid, password
try {
Statement stmt = conn.createStatement();
try {
ResultSet rset = stmt.executeQuery("select BANNER from SYS.V_$VERSION");
try {
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
}
finally {
try { rset.close(); } catch (Exception ignore) {}
}
}
finally {
try { stmt.close(); } catch (Exception ignore) {}
}
}
finally {
try { conn.close(); } catch (Exception ignore) {}
}
}
}
edit: On my computer it is here:
C:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\jdk\jre\lib\ext
Just put it in the application's runtime classpath. The file system paths covererd by the classpath depends on how you're executing the application.
Based on your question history I see that you're using JSP/Servlets, which thus means that it's a web application in flavor of a WAR file which runs in an appserver. In that case, the JAR file needs to go in webapp's own /WEB-INF/lib folder or in the appserver's own /lib folder.
If it were a plain vanilla Java application .class file with a main() method which is to be executed by java command, then you'd have to use the -cp (-classpath) argument to specify the runtime classpath. It takes a collection of (semi)colon separated disk file system paths.
If it were a JAR file, then it had to be specified in the Class-Path entry in JAR's /META-INF/MANIFEST.MF file. This can be relative to the java -jar command's working directory.
You should really avoid putting 3rd party libraries in JRE's /lib folder. This would potentially introduce classpath problems with all other existing applications which use the same JRE.

Categories