Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch: cannot convert from java.sql.Connection to com.mysql.jdbc.Connection

import java.io.IOException;
import java.sql.DriverManager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.*;

*// Here,in below 2 statement, I got 2 the same error as shown in title*

**Connection con = DriverManager.getConnection("localhost:3306", "root","simple");               
Statement stmt = con.createStatement();**
    if(stmt.execute(sql)){
    System.out.println("Sql Statement Executed.");
    }
    else
    {
        System.out.println("Sql Statement not eexecuted.");
    }
    if((unm != null) && (pwd != null)){
        RequestDispatcher rd =request.getRequestDispatcher("Home.jsp");
        rd.forward(request, response);
    }
}

}

I am trying to send my data from servlet to mysql server but in servlet I got the

error : "Type mismatch: cannot convert from java.sql.Connection to com.mysql.jdbc.Connection"

Can anyone suggest me the way to remove the error for my code. I am not getting any idea.

like image 653
Zealous Avatar asked Dec 28 '25 15:12

Zealous


2 Answers

Remove the import com.mysql.jdbc.* and use import java.sql.Connection. I think it would be ok.

like image 84
Erkan Akın Avatar answered Dec 30 '25 06:12

Erkan Akın


I think you're using the wrong connection string and the driver manager doesn't know how to instantiate the connection. The documentation has more info about the format.

It think the code should be something like

con = DriverManager.getConnection("jdbc:mysql://localhost/test","root","simple");

And I think there's a problem with the imports, as described in this other question: Type mismatch: cannot convert from Connection to Connection, and you need to import java.sql.Connection;

edit

To fix the DriverManager error you need to register the driver with the following code (taken from the mysql documentation)

    try {
        // The newInstance() call is a work around for some
        // broken Java implementations

        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
        // handle the error
    }
like image 35
Augusto Avatar answered Dec 30 '25 08:12

Augusto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!