klodye
klodye

Reputation: 103

Connecting to MySQL from Eclipse

I'm trying to connect to the MySql database from a Java servlet. I'm working in 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();
        }
    }

}

In the line

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

I get the following exception:

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

I downloaded the connector/J, extracted the jar file into Tomcat library folder and set it in the class path.

I have no idea what else I could have done wrong. It also says

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. 

I thank for any help in advance :-)

Upvotes: 0

Views: 4982

Answers (1)

JB Nizet
JB Nizet

Reputation: 691735

The problem is that the URL is incorrect. It should be

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

Just putting the jar file of the driver in your WEB-INF/lib folder should be sufficient. No need to modify the Tomcat installation. But you should really take care of closing the resultsets, statements and connections in a finally block, else your database will quickly run out of available connections.

You should also use a pooled DataSource as explained in the Tomcat documentation.

Upvotes: 1

Related Questions