2014-01-22 36 views
2
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); 
    } 
} 

} 

我想从servlet的把我的数据,MySQL服务器,但在servlet的我得到了类型不匹配:不能转换从java.sql.Connection中到com.mysql.jdbc.Connection

错误:“类型不匹配:无法从java.sql.Connection转换为com.mysql.jdbc.Connection“

任何人都可以为我的代码删除错误的方式。我没有任何想法。

回答

7

删除import com.mysql.jdbc.* 并使用import java.sql.Connection。我认为这样可以。

+0

是的,它甚至工作,但我想使用MySQL作为一个后端工具,并且DriverManager不能解决错误仍然来... – Zealous

+0

在快速ness,我忘了,它是一个连接接口提供的javase规范处理由DriverManger提供的对象> getConnection()...! – Zealous

1

我想你使用了错误的连接字符串,并且驱动程序管理器不知道如何实例化连接。 documentation有关于格式的更多信息。

它认为的代码应该像

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

我想有一个与进口问题,因为在这个其他问题描述:Type mismatch: cannot convert from Connection to Connection,你需要import java.sql.Connection;

编辑

要修复DriverManager错误,您需要使用以下代码注册驱动程序(取自mysql文档)

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 
    } 
+0

谢谢,Augusto给你回复,是的,已解决但是我还是得到了“DriverManager无法解决”的错误.. – Zealous

+0

你可能还没注册mysql驱动。请阅读这个[文档](http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-connect-drivermanager.html) – Augusto

-1

我回答一个老问题,但我碰到了同样的问题,我通过导入所有的图书馆解决它:

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; 

希望它能帮助。

相关问题