class not found exception com.mysql.jdbc.driver [duplicate] - java

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 7 years ago.
File structure of my project is:
-src
|
-pkg
|
-CoreServlet.java(servlet)
-Main.java
-Core.java(jdbc code is here)
core.java class:
package com.pkg;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class core{
private Connection connect = null;
private Statement statement =null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
String qwerty;
public void readDataBase() {
String userName = "ansh";
String password = "12345";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/glbitm", userName,password);
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from teachers");
resultSet.next();
qwerty = resultSet.getString(1);
} catch (Exception e) {
System.out.println(e);
}
}
}
coreServlet.java class :
package com.pkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class coreServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
core dao = new core();
dao.readDataBase();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></head>");
pw.println("<div>"+dao.qwerty+"</div>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}
When I am accessing dao.qwerty in my coreServlet.java in my tomcat server. I am getting class not found exception com.mysql.jdbc.driver and value of dao.qwerty is printed as null. Where I am doing wrong ?

You need to add the mysql connector in classpath.
http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.4/mysql-connector-java-5.1.4.jar
This connector jar acts as a mediator between database and the application for the flow of data. You can extract the class files from jar and see the details.

The java.lang.ClassNotFoundException is thrown when your code attempts to execute the following line
Class.forName("com.mysql.jdbc.Driver").newInstance();
This is a checked exception which always needs to be either caught inside a try/catch or if try/catch is not implemented, then this exception needs to be declared in the method.
There have been multiple resolutions provided in this thread, but from my experience if you are able to connect to your database from eclipse using data source explorer, then most likely reason is "mysql-connector-java-5.1.28-bin.jar" is not copied into the your tomcat's lib directory.
The mysql connector for java can be downloaded from http://dev.mysql.com/downloads/connector/j/

You have not set the mysql-connector in your path.Set that first and everything else will be done
What is JConnector ?
Java does not know SQL so every statement you want to execute using the sql driver will get converted to sql constructs and the result that is returned my mysql is also converted into java understandable constructs.
hope it helps

Related

Servlet Database URL

I'm trying to have a servlet to connect and interact with a database. I'm very new at this topic, so there probably are a couple of big issues, but the main problem I'm stuck at is how to get the database URL.
This is the servlet (I'm trying to keep it as light as possible)
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class qaServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstName = request.getParameter("question");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/qaDatabase", "root", "");
//^HOW DO I GET THE RIGHT URL?^
PreparedStatement ps = con.prepareStatement("insert into faq values('1','question','sì');");
int i = ps.executeUpdate();
}
catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
First, it is better to use e2.printStackTrace(); instead of System.out.println(e2); when debugging.
Second, as the exception has shown, the actual problem was missing JAR file with JDBC driver, which has to be either in the WEB-INF/lib folder of your application, or in Tomcat's lib folder.
When developing, don't forget to republish your project after adding the driver's JAR file.

How do I import .jar and use its class and also how do i use stmt from a .jar file in netbeans?

It's 1:37am here so I'm greeting you all a good day.
I've got a problem here and I'm really really new to java. Please have patience on me. :(
I've got a .jar file that I imported to my Libraries in my netbeans project. It's called dbconnect.jar. I want to create a statement in my Fruits.java that will change my stmt statement (from inside dbconnect.jar) to whatever mysql statement i want it to be (specifically, I want to add fruits to my db). Here's my project map:
So inside my dbconnect.jar contains the class Dbconnect. Here are the contents of Dbconnect:
package dbconnect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Dbconnect {
public Connection conn = null;
public Statement stmt = null;
public ResultSet rs = null;
public Dbconnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String Host = "jdbc:mysql://localhost/dbname";
String Username = "root" ;
String Password = "";
conn = DriverManager.getConnection(Host, Username, Password);
stmt = conn.createStatement();
}catch(Exception e){
e.printStackTrace();
}
}
}
By the way, I'm using xampp for Apache and Mysql.
So my questions are, how do I call/import this dbconnect.jar of mine so I can use it in Fruits.java (and if possible, am I able to use extends here?) and how do I make it so that I can edit the stmt part in dbconnect.jar using Fruits.java ?
This is currently what's inside the add button from my UI in Fruits.java:
I really need help with this. Thank you so much in advance!
Oh and I'm still a starter. So I hope there will be no advanced codes. Thanks again!
And yes, I'm using JFrame. Here's what it looks like for now.
Since, you have Dbconnect.jar on your classpath you can just say something like this in your Fruit.java class:
Dbconnect db = new Dbconnect();
This will create a new object of Dbconnect class with name db.
In order for you to be able to edit the statement you'll have to create a new method and not just call it in the constructor.
Here is an example:
public void connect(String myStatement) {
/* Do Something */
}
You can then call connect() function on db object you created before.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver during Dynamic Web Project creation in java

I am designing a registration page using MVC design pattern. I have made a class file which will input the parameters into the database using sql commands but i am getting
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Here is the code
package src.service;
import java.sql.*;
public class RegisterService {
public void addToDatabase(String name, String id, String email, String password){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
// Create a statement
Statement myStatement = myConn.createStatement();
String sql = "insert into userid values(" + id + ", '" + name + "', '" + email + "', '" + password + "')";
myStatement.executeUpdate(sql);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I have imported the driver in my lib folder of the project, imported it in build path, imported it in tomcat server in the folder tomcatv7>lib by creating a lib folder. Still it is showing the same error. Kindly help.
You need to setup the DB Connection in server.xml
follow this tutorial :
http://examples.javacodegeeks.com/core-java/mysql-connector-for-java-how-to-install-in-eclipse-and-tomcat/
and
https://www.mulesoft.com/tcat/tomcat-mysql
as well as you need to download MySQL Connector from:
http://dev.mysql.com/downloads/connector/j/
and copy the jar file to "C:\tomcat7\lib"
You should add MYSQL JDBC LIBRARY to your project
and also import
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
This worked for me---
This solution is only for Dynamic web projects.
Steps--
1)Create a Dynamic Web project
2)I added the "mysql-connector-java-5.1.48-bin" jar in WebContent/WEB-INF/lib folder.
2) Create a tomcat server
3)inside src create a demo servlet--
package com.luv2code.testdb;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
/**
* Servlet implementation class TestDbServlet
*/
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setup connection variables
String user = "springstudent";
String pass = "springstudent";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
4)Just right click and run as run on server select ur tomact server
Remember before all these you need to create ur db schema,
here i have used mysql workbench.
Mysql part is not covered in this answer.
If this does not work, try adding the msql connector jar inside tomcat/lib folder

java database connection end up with the db:java.sql.SQLException: No suitable driver found

i am brand new to Java . Here i am trying to connect to mysql database here my code:
package Services;
package Services;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class LoginService {
private static final String USERNAME="root";
private static final String PASSWORD="";
private static final String CONNECTION_STRING="jdbc:mysql://localhost/testdb";
public void Authenticate(String uname,String password){
Connection connection=null;
Statement statement=null;
ResultSet result =null;
try{
//Class.forName("com.mysql.jdbc.Driver").newInstance();//if java 6 or higher there is no need to load cass
connection =(Connection)DriverManager.getConnection(CONNECTION_STRING,USERNAME,PASSWORD);
System.out.println("Connection to the database is established ");
}catch(SQLException e){
System.out.println("Can't connect to db:" +e );
}
}
}
This end up with an error like this:
Can't connect to db:java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/testdb
i have added the jar file and by right clicking in it added the same to build path;what wrong with my code .
You have to download the JDBC driver ..
after that ... add it to your library..
You can read this! It's really simple after you get the idea!
here is the link! http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html
And this one! http://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/
Good luck!

ClassNotFoundException oracle.jdbc.driver.OracleDriver only in servlet, using Eclipse [duplicate]

This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
Closed 7 years ago.
The code below fails on the line:
Class.forName("oracle.jdbc.driver.OracleDriver");
with the error:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
The two printlns print:
Wed_Jun_22_11:18:51_PDT_2005
false
This makes me think the class exists and can be found. Also this exact same class works in an a non-servlet application.
I have rebooted everything multiple times and regenerated the application/servlet multiple times. All values have been hard coded to make it simple and short.
private static Connection getDBConnection() throws Exception {
System.out.println(oracle.jdbc.driver.OracleDriver.BUILD_DATE);
System.out.println(Class.class.desiredAssertionStatus());
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "SYSTEM", "pass");
}
full servlet that fails:
package servletClass_3;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class OneMoreBookStore
*/
#WebServlet("/OneMoreBookStore")
public class OneMoreBookStore extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
private static Connection getDBConnection() throws Exception {
System.out.println(oracle.jdbc.driver.OracleDriver.BUILD_DATE);
System.out.println(Class.class.desiredAssertionStatus());
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "SYSTEM", "pass");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
Connection con = getDBConnection();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This application works:
package servletClass_3;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnect {
private static Connection getDBConnection() throws Exception {
System.out.println(oracle.jdbc.driver.OracleDriver.BUILD_DATE);
System.out.println(Class.class.desiredAssertionStatus());
//load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "SYSTEM", "pass");
}
public static void main(String[] args) {
try
{
Connection con = getDBConnection();
System.out.println("connection worked");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I'm using:
Eclipse JavaEE 1.4.2
Tomcat 7
jdk1.7
Oracle 11g R2
Windows 7 64bit
Probably you aren't deploying the oracle driver with your application.
You have several options:
You can place the driver jars in your WEB-INF/lib folder
You export it with your application. -> Right Click on Project -> Build Path-> Configure Build Path... -> Order and Export -> Check the drivers.
Place the driver jars in a shared or library extension folder of your application server. (You should go with option one or two though.)
You must include the ojdbc6.jar file in the Deployment Assembly of the Project...
select the web project which contains the jsp file...
select Project tab in the menu bar in Eclipse
select properties in the drop down menu
select Deployment Assembly
Add your ojdbc6.jar file in it.
Try this, change the oracle.jdbc.driver.OracleTypes to oracle.jdbc.OracleTypes

Categories

Resources