samedi 28 mars 2015

Difference between location of MySQL Drivers between Java Application and Java Web Application?

I'm working with MySQL integration. I am using JDK 8 with Eclipse Luna EE, Tomcat 8.0 and MySQL 5.1.34


I have 2 projects, one is a Java Web Application, the other is a Dynamic Web Project.



public void connectToDB(String host, String dbName, int port, String username, String password){

try
{
String url = "jdbc:mysql://" + host + ":" + port + "/" + dbName;

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

dbConnection = DriverManager.getConnection(url, username, password);

System.out.println("Successfully connected to database!");
}
catch(Exception e){
System.out.println("Error accessing database!" + e.getMessage());
}
}


I have a few questions:



  1. The code doesn't work if I remove the "Class.forName(...)". Why is that so? I read I didn't need this for Java 5 and up (I am using Java 8), but it seems like my code won't work without it.

  2. For the JAVA APPLICATION project, the way I import the Driver is through Project Properties -> Java Build Path -> Libraries -> Add External JAR -> MySQL Driver ... For the DYNAMIC WEB APPLICATION project, if I import the same way (in the build path), it does not work! However, if I copy paste the MySQL Driver JAR file to the $CATALINA_HOME/lib, it works! Why is this the case?


Hoping someone can clear it up. Thanks!





Aucun commentaire:

Enregistrer un commentaire