SkollSunman
SkollSunman

Reputation: 27

Cannot connect to a mysql database with JSP, Glassfish

I have previous JSP experience but with using Tomcat and Resin and I would like to connect to a mySQL database using Glassfish and hoped that more or less copy and pasting the code would work.

The code is:

try {
        Class.forName("org.gjt.mm.mysql.Driver");
    } catch (Exception E) {
        System.out.println("First: " + E);
    }

Connection conn = DriverManager.getConnection("jdbc:mysql://xxx.xx.xx.xx:xxxx/DBName", "Username", "Password");

The errors I get when I look into my server logs are

[#|2012-03-09T13:50:21.900+0000|INFO|glassfish3.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=67;_ThreadName=Thread-1;|First: java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver|#]

[#|2012-03-09T13:50:22.009+0000|INFO|glassfish3.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=67;_ThreadName=Thread-1;|java.sql.SQLException: No suitable driver found for jdbc:mysql://xxx.xx.xx.xx.xx/SmarterStudents|#]

I have put the mysql-connector-java-5.0.7-bin.jar into the domain/lib folder and threw it into the WEB-INF/lib folder just to be safe and it still wouldn't work for me.

I'm at my wit's end now, I just don't know what to do. D:

Upvotes: 0

Views: 1846

Answers (2)

BalusC
BalusC

Reputation: 1109810

You're using the old and deprecated driver class name for the very first releases of the MySQL JDBC driver org.gjt.mm.mysql.Driver when it was still a hobby project, while you're using one of the more recent releases of the MySQL JDBC driver which has the driver class name com.mysql.jdbc.Driver.

Fix the classname accordingly.

Class.forName("com.mysql.jdbc.Driver");

Make sure that you're reading the official MySQL JDBC driver documentation instead of some random and heavily outdated resource/book/tutorial.

As to the placement of the JAR file, when you're managing the connections yourself in your web application, the JAR can be placed in both server's own /lib or webapp's /WEB-INF/lib. But when you're letting the server manage the connections (which will usually use a shared connection pool which is way much faster), then the JAR must be placed in server's own /lib folder. The one in the deployed webapp(s) will be ignored anyway.

Upvotes: 3

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

Try working with JdbcOdbcDriver , but generally they say it should be used as a last resort.

try
{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:db","root","root");
}catch(Exception e){
     e.printStackTrace();
}

This should work for MySQL database, you need to install the connector for this as well, and the username and password generally for MySQL is root and root, respectively.

Upvotes: -2

Related Questions