2011-10-15 104 views
0

我試圖從Java servlet連接到MySql數據庫。我正在Eclipse IDE中工作。從Eclipse連接到MySQL

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    Connection con = null; 
    try { 
     Class.forName("com.mysql.jdbc.Driver").newInstance(); 
     con = DriverManager.getConnection("jdbc:mysql//localhost:3306/try", "root", "password"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    if (request.getParameter("select1") != null) { 
     PrintWriter out = response.getWriter(); 
     String select1 = (String) request.getParameter("select1"); 
     int no = Integer.parseInt(select1); 
     String query = "SELECT * FROM try.try where id='" + no + "'"; 
     out.print("<option>---select one---</option>"); 
     try { 
      Statement stmt = (Statement) con.createStatement(); 
      ResultSet rs = stmt.executeQuery(query); 
      while (rs.next()) { 
       out.print("<option>" + rs.getString("output") + "</option>"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

在線路

con = DriverManager.getConnection("jdbc:mysql//localhost:3306/try", "root", "password")

我出現以下情況例外:

java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/try Exception.

我下載的連接器/ J,提取的jar文件到Tomcat庫文件夾和將其設置在課程路徑中。

我不知道還有什麼我可以做錯了。它還說

The JAR file C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\mysql-connector-java-5.1.18-bin.jar has no source attachment. 

我感謝所有幫助提前:-)

回答

1

的問題是,該URL不正確。它應該是

jdbc:mysql://localhost:3306/try 
      ^-- you missed the colon here 

只需將驅動程序的jar文件放入您的WEB-INF/lib文件夾就足夠了。無需修改Tomcat安裝。但是,您應該確保在finally塊中關閉結果集,語句和連接,否則您的數據庫將很快耗盡可用連接。

您還應該按照Tomcat documentation中的說明使用合併的數據源。

+0

我糾正了關閉,但主要問題仍然沒有解決,即使我把連接器放入WEB-INF/lib文件夾中 – klodye

+0

您是否在Eclipse下刷新了項目?您是否在Web App Libraries節點下看到驅動程序的jar文件? –

+0

是的,我做了...但沒有改變 – klodye