【问题标题】:Connecting to MySQL from Eclipse从 Eclipse 连接到 MySQL
【发布时间】:2011-10-15 13:36:42
【问题描述】:

我正在尝试从 Java servlet 连接到 MySql 数据库。我在 Eclipse IDE 中工作。

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. 

提前感谢您的帮助:-)

【问题讨论】:

    标签: java mysql servlets connection


    【解决方案1】:

    问题是 URL 不正确。应该是

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

    只需将驱动程序的 jar 文件放在您的 WEB-INF/lib 文件夹中就足够了。无需修改Tomcat安装。但是你真的应该注意在 finally 块中关闭结果集、语句和连接,否则你的数据库将很快耗尽可用的连接。

    您还应该使用Tomcat documentation 中解释的池化数据源。

    【讨论】:

    • 我更正了关闭,但主要问题仍未解决,即使我将连接器放入 WEB-INF/lib 文件夹
    • Eclipse下的项目刷新了吗?在 Web App Libraries 节点下看到驱动的 jar 了吗?
    • 是的,我做了...但没有任何改变
    • 哦,谢谢。如此愚蠢的错误(我现在会永远记住:-D)。再次感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多