java.lang.ClassNotFoundException error in the Servlet code - java

I'm having java.lang.ClassNotFoundException error after executing the above code.I will be very glad if someone could look into this code. I'm using oracle 11g database and all database connection details are correct. Also having HTTP Status 500 – Internal Server Error on while executing the code.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Search extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String rollno=request.getParameter("roll");
int roll=Integer.valueOf(rollno);
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from result where rollno=?");
ps.setInt(1,roll);
out.print("<table width=50% border=1>");
out.print("<caption>Result:</caption>");
ResultSet rs=ps.executeQuery();
/* Printing column names */
ResultSetMetaData rsmd=rs.getMetaData();
int total=rsmd.getColumnCount();
out.print("<tr>");
for(int i=1;i<=total;i++)
{
out.print("<th>"+rsmd.getColumnName(i)+"</th>");
}
out.print("</tr>");
out.print("</tr>");
/* Printing result */
while(rs.next())
{
out.print("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"
</td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td></tr>");
}
out.print("</table>");
}catch (Exception e2) {e2.printStackTrace();}
finally{out.close();}
}
}
I'm using oracle 11g database and all database connection details are correct.
I'm using oracle 11g database and all database connection details are correct.

you should add JDBC driver into the build path , Or add it as a dependency to your POM

Related

ucanaccess SQL Exception: invalid cursor state: identified cursor is not open

I am a little bit confused,
I am trying to insert multiple rows to MS Access database from a java program using ucanaccess Java library.
I don't understand why the above (check title) SQL Exception is thrown when calling the 2nd insertRow() method?
The Exception is NOT thrown either by calling con.setAutoCommit(false); & con.commit(); methods or by re-executing the SQL query using the command rs = st.executeQuery(sql);. I also do not understand why the problem is solved by doing one of the above. What changes?
Thanks in advance.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class db1 {
private Connection con;
protected Statement st;
protected ResultSet rs;
public db1() {
connect();
}
public void connect() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
String db = "jdbc:odbc:Database1";
con = DriverManager.getConnection
("jdbc:ucanaccess://C:\\Users\\Κώστας\\Desktop\\Database1.accdb");
st = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT)
// con.setAutoCommit(false);
String sql = "select * from TableA";
rs = st.executeQuery(sql);
rs.insertRow();
// rs = st.executeQuery(sql);
rs.insertRow(); // HERE the SQL Exception is thrown.
// con.commit();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new db1();
}
}
UCanAccess has some known issues with updatable ResultSets because it uses triggers on the HSQLDB backing tables to push the changes to the Access database file. A side effect of those triggers is that they can leave the HSQLDB ResultSet in an invalid state.
The problem you are experiencing may not manifest itself with con.setAutoCommit(false); because the triggers probably don't flush the changes to the Access database until the JDBC transaction is committed.

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.

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

Why do I keep getting the SQL parameter index out of range exception?

I looked at similar questions and I followed the syntax for writing queries for inserting into a database but I keep getting this exception. I'm clearly not seeing something. It stops running at " insertStatement.setInt(1, schoolID);" . I read that this means that the query is not in its proper syntax. Please show me where I went wrong. I can't see it at all.
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
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 jpa.entities.School;
/**
*
* #author Timothy
*/
#WebServlet(name = "SchoolFormServlet", urlPatterns = {"/SchoolFormServlet"})
public class SchoolFormServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParseException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
ServletContext sc = this.getServletContext();
sc.getAttribute("schoolForm");
Integer schoolId = Integer.parseInt(request.getParameter("schoolID"));
String schoolName = request.getParameter("schoolName");
Integer periods = Integer.parseInt(request.getParameter("periods"));
Integer repeatDays = Integer.parseInt(request.getParameter("repeatDays"));
String scheduleBlock = request.getParameter("scheduleBlock");
Integer semesters = Integer.parseInt(request.getParameter("semesters"));
String rangeForLunch = request.getParameter("rangeForLunch");
String schoolYear = request.getParameter("schoolYear");
initAndExecuteQuery(schoolId,schoolName,semesters,periods,repeatDays,scheduleBlock,rangeForLunch,schoolYear);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SchoolFormServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet SchoolFormServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(SchoolFormServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(SchoolFormServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
public void initAndExecuteQuery(Integer schoolID,String schoolName, Integer semesters,Integer periods,Integer repeatDays,String scheduleBlock,String rangeForLunch, String schoolYear) {
// JDBC driver name and database URL
String jdbcDriver ="com.mysql.jdbc.Driver";
String url ="jdbc:mysql://173.194.104.102:3306/hssp_schema?zeroDateTimeBehavior=convertToNull";
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
// Database credentials
String userName = "admin_aamir";
String passWord = "tommybrown";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, userName , passWord);
// Execute SQL query
String sql;
sql = "INSERT INTO School VALUES ('"+schoolID+" ','"+schoolName+" ','"+semesters+" ','"+periods+" ','"+repeatDays+" ','"+scheduleBlock+" ','"+rangeForLunch+" ','"+schoolYear+" ')";
PreparedStatement insertStatement = connection.prepareStatement(sql);
insertStatement.setInt(1, schoolID);
insertStatement.setString(2,schoolName);
insertStatement.setInt(3,periods);
insertStatement.setInt(4,repeatDays);
insertStatement.setString(5,scheduleBlock);
insertStatement.setString(6,rangeForLunch);
insertStatement.setString(7,schoolYear);
insertStatement.executeQuery();
insertStatement.close();
connection.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
You need to put question marks in the SQL string to tell it that it has parameters -- instead of appending them straight in.
sql = "INSERT INTO School VALUES(?, ?, ? ...)
The MySQL connector implementation will do the hard work of replacing those question marks with the values of the parameters you set (it doesn't just paste them in, as your code does, since that would make it vulnerable to SQL injection).
Proper syntax is
INSERT INTO TABLENAME (FIELD1, FIELD2, FIELD3) VALUES (?, ?, ?)
so you need the names of the columns within first parens and the same number of ? in the second. Then your setX(1, value) statements fill in where the question marks are before execution.
inside School( ...... ) put your database table column name, inside values(?,?,?.....) put the question mark based on how many column name you wanted to insert to database, for your current case is 8 column so put 8 question marks.
String sql;
sql = "INSERT INTO School(schoolID,schoolName,semesters,periods,repeatDays,scheduleBlock,rangeForLunch,schoolYear) VALUES (?,?,?,?,?,?,?,?)";
PreparedStatement insertStatement = connection.prepareStatement(sql);
insertStatement.setInt(1, schoolID);
insertStatement.setString(2,schoolName);
insertStatement.setInt(3,periods);
insertStatement.setInt(4,repeatDays);
insertStatement.setString(5,scheduleBlock);
insertStatement.setString(6,rangeForLunch);
insertStatement.setString(7,schoolYear);
// you have missing 1 line for number 8 , since you wanted to insert 8 data into 8 column
insertStatement.executeQuery();
insertStatement.close();
connection.close();
Method 1:
Write the following code
String sql;
sql = "INSERT INTO School VALUES ('"+schoolID+" ','"+schoolName+" ','"+semesters+" ','"+periods+" ','"+repeatDays+" ','"+scheduleBlock+" ','"+rangeForLunch+" ','"+schoolYear+" ')";
PreparedStatement insertStatement = connection.prepareStatement(sql);
int valid = insertStatement.executeUpdate();
if(valid == 1)
System.out.println("insertion successfull");
else
System.out.println("problem while inserting data in database");
Hope it works for you.It works in my case.
Method 2:
Write the following code
String sql;
sql = "INSERT INTO School VALUES ('"+schoolID+" ','"+schoolName+" ','"+semesters+" ','"+periods+" ','"+repeatDays+" ','"+scheduleBlock+" ','"+rangeForLunch+" ','"+schoolYear+" ')";
sql = "INSERT INTO School VALUES(?,?,?,?,?,?,?,?)";
PreparedStatement insertStatement = connection.prepareStatement(sql);
insertStatement.setInt(1, schoolID);
insertStatement.setString(2,schoolName);
insertStatement.setInt(3,semesters) // you forgot to write this statement assuming the data types are correct
insertStatement.setInt(4,periods);
insertStatement.setInt(5,repeatDays);
insertStatement.setString(6,scheduleBlock);
insertStatement.setString(7,rangeForLunch);
insertStatement.setString(8,schoolYear);
int valid = insertStatement.executeUpdate();
if(valid == 1)
System.out.println("insertion successfull");
else
System.out.println("problem while inserting data in database");
Hope you understand both the methods

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

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

Categories

Resources