1

I am using NetBeans 7.0.1 IDE for JSP/servlet I am trying to make a database connection for my project. Already downloaded the jar file 'mysql-connector-java-5.1.24-bin.jar' pasted it to jdk's jre/lib dir, also added it to my netbean projects libraries dir. then I created a servlet and wrote the following code:

import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class tstJDBC extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try{
    String dbURL = "jdbc:mysql://localhost:3306/murach";

         String username="root";
         String password="1234";

         Connection con2 = DriverManager.getConnection(dbURL, username, password);
          String query = "insert into tblUser1(firstname) values('shaon')";

          Statement statmnt = con2.createStatement();
          statmnt.executeUpdate(query);
    }

    catch(SQLException e)
    {
        e.printStackTrace();
    }
}

}

But it can establish the connection. From the line Connection con2, its directly going to catch() block ; without executing the query.

Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
Shaon Hasan
  • 730
  • 7
  • 17

2 Answers2

0

Try loading the driver prior to using the DriverManager class.

try{
     String dbURL = "jdbc:mysql://localhost:3306/murach";

     String username="root";
     String password="1234";


     Class.forName("com.mysql.jdbc.Driver");//load driver

     Connection con2 = DriverManager.getConnection(dbURL, username, password);
     String query = "insert into tblUser1(firstname) values('shaon')";

     Statement statmnt = con2.createStatement();
     statmnt.executeUpdate(query);
}

From O'Reilly:

Before you can use a driver, it must be registered with the JDBC DriverManager. This is typically done by loading the driver class using the Class.forName( ) method:

This is required since you have placed the library within the JDK/lib folder which I'm assuming is loaded using a different ClassLoader than the one used by your application. Since different class loaders were used the automatic registration that takes place by JDBC 4.0+ drivers will not take effect. You could try to place the driver jar file within the lib of your application server, which should use the same ClassLoader of your application. See: When is Class.forName needed when connecting to a database via JDBC in a web app?

Regarding Automatic Registration

In JDBC 4.0, we no longer need to explicitly load JDBC drivers using Class.forName(). When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from among the JDBC drivers that were loaded at initialization and those loaded explicitly using the same class loader as the current application.

The DriverManager methods getConnection and getDrivers have been enhanced to support the Java SE Service Provider mechanism (SPM). According to SPM, a service is defined as a well-known set of interfaces and abstract classes, and a service provider is a specific implementation of a service. It also specifies that the service provider configuration files are stored in the META-INF/services directory. JDBC 4.0 drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC driver's implementation of java.sql.Driver. For example, to load the JDBC driver to connect to a Apache Derby database, the META-INF/services/java.sql.Driver file would contain the following entry:

org.apache.derby.jdbc.EmbeddedDriver

Let's take a quick look at how we can use this new feature to load a JDBC driver manager. The following listing shows the sample code that we typically use to load the JDBC driver. Let's assume that we need to connect to an Apache Derby database, since we will be using this in the sample application explained later in the article:

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection conn =
    DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);

But in JDBC 4.0, we don't need the Class.forName() line. We can simply call getConnection() to get the database connection.

Source

Regarding Service Loaders

For the purpose of loading, a service is represented by a single type, that is, a single interface or abstract class. (A concrete class can be used, but this is not recommended.) A provider of a given service contains one or more concrete classes that extend this service type with data and code specific to the provider. The provider class is typically not the entire provider itself but rather a proxy which contains enough information to decide whether the provider is able to satisfy a particular request together with code that can create the actual provider on demand. The details of provider classes tend to be highly service-specific; no single class or interface could possibly unify them, so no such type is defined here. The only requirement enforced by this facility is that provider classes must have a zero-argument constructor so that they can be instantiated during loading.

A service provider is identified by placing a provider-configuration file in the resource directory META-INF/services. The file's name is the fully-qualified binary name of the service's type. The file contains a list of fully-qualified binary names of concrete provider classes, one per line. Space and tab characters surrounding each name, as well as blank lines, are ignored. The comment character is '#' ('\u0023', NUMBER SIGN); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8.

If a particular concrete provider class is named in more than one configuration file, or is named in the same configuration file more than once, then the duplicates are ignored. The configuration file naming a particular provider need not be in the same jar file or other distribution unit as the provider itself. The provider must be accessible from the same class loader that was initially queried to locate the configuration file; note that this is not necessarily the class loader from which the file was actually loaded.

Source

Community
  • 1
  • 1
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • but Class.forName("com.mysql.jdbc.Driver"), is used for manually loading the driver. if i already added mySQL JDBC connector to library than why wud i need to use this? confused.. :-( – Shaon Hasan Apr 18 '13 at 09:27
  • @ShaonHasan It's used for loading classes. JDBC drivers have a static initializer which is roughly analogous to a constructor, but for a class rather than an object. inside this, the driver registers itself with your DriverManager, so you can use it to obtain resources like connections. the initializer is run when the class is loaded. Class.forName just kicks this process off. You could also add an import statement to the java file as `import com.mysql.jdbc.Driver` or add the same to your environment variable for build path – Ajo Koshy Apr 18 '13 at 09:57
  • @AjoKoshy Would different class loaders come into play here? – Kevin Bowersox Apr 18 '13 at 10:20
  • @KevinBowersox Well you can call multiple loaders. but all wont be having access to the same url as provided – Ajo Koshy Apr 18 '13 at 10:28
  • @ShaonHasan Any luck? – Kevin Bowersox Apr 18 '13 at 10:34
0

just Keep the "mysql-connector-java" in "C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext" the "jdk1.7.0_25" is my version of jdk may be you have different version but will must have the sub folders "\jre\lib\ext" inside that.

Muhammad
  • 6,725
  • 5
  • 47
  • 54