Servlet to mysql jdbc connection class not found exception - java

I am trying to connect servlet to mysql database in netbeans 8 and jdk 8 and glassfish server. i have also included mysqlconnector jar file in libraries but am getting
class not found exception at Class.forName("com.mysql.jdbc.Driver")
piece of my code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class sqltest1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String pass = request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo", "root", "root");
PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("Correct login credentials");
}
else {
out.println("Incorrect login credentials");
}
}
}

Try reAdding jar file into java build path and clean than recompile.
Your code looks fine.

Check mysql driver jar on your classpath and also verify proper mysql driver jar.

Related

What is missing in the following steps to test db connection from eclipse using tomcat and java ?am getting 404 error

My code to test db connection from eclipse is given below
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.*;
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user="user01";
String pass="pass01";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.cj.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);
}
}
am getting 404 error when i run this on server .I have added mysql-connector-java8.0.11.jar to lib folder of webinf.am using tomcat9 with java14 .
Normally, if you are getting a 404 error it means that the page is not found (Probably if your url isn't correct), if there is an error in the doGet Method "The connection to the database part" the server will respond with a 500 error.
https://www.codejava.net/java-ee/servlet/solved-tomcat-error-http-status-404-not-found
Let me know if that helped.

Java JDBC: Cannot insert Data into Database

I'm coding for hours to insert data into my SQL database, but nothing happens.
I even can't debug Java, because I don't get any output of my console.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author xxx
*/
public class MyServlet extends HttpServlet {
private static final String URL = "jdbc:mysql://localhost:3306/userdata";
private static final String USER = "root";
private static final String PASSWORD = "root";
private static final DecimalFormat DF2 = new DecimalFormat("#.##");
private static Connection con;
private static Statement stmt;
private static ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
try {
String myDriver = "com.mysql.jdbc.Driver";
try {
Class.forName(myDriver);
// opening database connection to MySQL server
con = DriverManager.getConnection(URL, USER, PASSWORD);
// getting Statement object to execute query
// the mysql insert statement
String query = "INSERT INTO customers (customer, currency, amount) values ('Name', 'Currency', 100);";
stmt.executeUpdate(query);
// execute the preparedstatement
// executing SELECT query
rs = stmt.executeQuery(query);
con.close();
stmt.close();
rs.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
What did I wrong, that nothing happens? Even if I use this code for Java-Classes (not Servlets), I only receive an compile error, but without message.
I'm using the IDE Netbeans and mysql DB is the MySQL Workbench. The Java Class is using the main method.
Update:
I've tested following Code with IntelliJ:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/userdata";
String user = "root";
String password = "root";
String query = "Insert into customers (customer, currency, amount) values('Michael Ballack', 'Euro', 500)";
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement pst = con.prepareStatement(query)) {
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(JdbcMySQLVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
private static class JdbcMySQLVersion {
public JdbcMySQLVersion() {
}
}
I can insert data into the MySQL database.
In Netbeans this code won't work, although I've implemented the MySQLConnector. I don't know why, but Netbeans seems hard to handle.
In the servlet code, I don't see you ever write anything to out. So nothing is being sent back to the browser, even if it compiled. You could write your SQL exception to the out writer you created. To be more precise add this in your exception: out.println(sqlEx.printStackTrace()); That should at least show what exception you are getting back to the browser.
What is the compile error you get outside of a servlet?
This maybe obvious, but to get JDBC stuff to work on your server, you need to have the MySQL server installed, started and configured. The table referenced has to be defined, etc. You could check this outside of the Java servlet environment with the tools provided with MySQL.
your code can not compile, you miss catch exception for second 'try'.
Where do you use this class to run, if you run a java class, this class must contain main() function?
you should use some IDEs like eclipse or IntelliJ to code, it help you detect the error easier.
I found the solution. If you are using Netbeans with the Glassfish-Server and you want your servlet to save data into the database, you have to make sure that Netbeans has installed the Driver of your Database Connector (e.g. MySQL Connector). But you also have to configurate your server (e.g. Glassfish) which will support the DB Connector drivers.
In my case my Server didn't load the DB Connector Driver so the JDBC Code couldn't be executed.
Here's a useful link to configurate the Glassfish Server: https://dzone.com/articles/nb-class-glassfish-mysql-jdbc

ClassNotFoundException / mysql jdbc driver [duplicate]

This question already has answers here:
ClassNotFoundException: com.mysql.jdbc.Driver. JDBC MySQL driver for web application [duplicate]
(3 answers)
Closed 4 years ago.
I have created a login and registration page but when CREATE ACCOUNT button is clicked the data is not getting stored into the data base. It gives a exception saying
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"
I have added the mysql jar file in my project.
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/loginandregister")
public class loginandregister extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String options=request.getParameter("button");
System.out.println(options);
PrintWriter pw=response.getWriter();
if(options.equals("LOGIN")) {
String username=request.getParameter("loginid");
String password=request.getParameter("loginpassword");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/loginclass","root","root");
PreparedStatement login=conn.prepareStatement("select * from user_info where username=? and userpassword=?");
login.setString(1, username);
login.setString(2, password);
ResultSet rs=login.executeQuery();
if(rs.next()) {
pw.println("Welcome");
pw.println("Welcome"+username);
}else {
pw.println("Error");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
if(options.equals("CREATE ACCOUNT")) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/loginclass","root","root");
PreparedStatement register=conn.prepareStatement("insert into user_info values (?,?,?,?,?,?)");
String firstname=request.getParameter("fname");
String lastname=request.getParameter("lname");
String email=request.getParameter("email");
String phone=request.getParameter("phone");
String uname=request.getParameter("uname");
String pass=request.getParameter("password");
register.setString(1, firstname);
register.setString(2, lastname);
register.setString(3, email);
register.setString(4, phone);
register.setString(5, uname);
register.setString(6, pass);
register.executeUpdate();
}// try
catch (Exception e) {
e.printStackTrace();
}//catch
}// if create acc.
}// dopost
}//class
I think you need to add the jar in your tomcat directory's lib folder. Add the jar there and do a restart of the server.
This might do it for you.

com.mysql.jdbc.Driver showing null on the browser

Hi I am having some trouble while I am trying to access my database. The connection to the database is not getting established.
In the web browser I am getting the following output:
In Connection Db
In try before registering driver
null
Below is the code snippet I am using to establish the connection.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ConnectionDB extends HttpServlet {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Data";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
pw.println("<h2>In Connection Db</h2>");
try {
//STEP 2: Register JDBC driver
pw.println("<h2>In try before registering driver</h2>");
Class.forName("com.mysql.jdbc.Driver");
pw.println("<h2>In try</h2>");
//STEP 3: Open a connection
con = DriverManager.getConnection(DB_URL,USER,PASS);
pw.println("<h2>After connection</h2>");
stmt = con.createStatement();
My classpath variable is set as follows
CLASSPATH = C:\Database\mysql-connector-java-5.1.27\mysql-connector-java-5.1.27-bin.jar;
Thanks in advance.
You may want to specify the port number for the JDBC URL. For MySQL this is usually 3306. So, your JDBC URL should be:
jdbc:mysql://127.0.0.1:3306/Data
However, you may find that the root cause if because your mysql connector is not in the /WEB-INF/lib folder which participates in the webapp's runtime classpath. Just copy the JAR file straight in the directory /WEB-INF/lib and rebuild/redeploy/restart.
In addition, I assume that you are using a Java Application Server (as you are creating Servlets). Therefore, I would consider using a JDBC Connection Pool as an alternative.

Respond to a get request in java using a database

I'm trying to respond to a get request in java using a database. But it throws some error which I don't know a clue how to fix it.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
try{
//Accessing driver from the JAR file
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
//Connect to Clockie's database
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/database", "root", "root");
//Here we create our query
String sql = "" +
"SELECT * " +
"FROM profiles " +
"WHERE profileId = '27'";
PreparedStatement statement = con.prepareStatement(sql);
ResultSet result = statement.executeQuery();
String xmls = "";
result.next();
xmls = result.getString("firstName") + " "+result.getString("lastName");
System.out.println(xmls);
resp.getWriter().println(xmls);
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
}
Everything is fine though, if I set the doGet code block inside the a main method? I'm new to Java pls help!
EDIT:
the exception is "com.mysql.jdbc.Driver";
Print out the full stack trace using e.printStackTrace(); in your catch block.
You may not have the mysql-connector jar which contains com.mysql.jdbc.Driver on your classpath. Check your classpath by printing it out using:
System.out.println("classpath = " + System.getProperty("java.class.path"));

Categories