2014-01-22 42 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.*; 

希望它能幫助。

相關問題