1

I am a java beginner and trying to insert a row in db. This is first time in java i am performing insertion operation. For around 2 Hrs i was googling and frustated and cannot solve my error. I called my friend and he gave live support for me in team viewer and added just one line of code to my program.

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

Can anyone please explain why we need to include this in my code before connection string. Is it necessary to place my code there each and every time. Please Explain me in Detail.

Java Beginer
  • 321
  • 2
  • 16
  • Maybe http://stackoverflow.com/questions/3816015/sqlexception-no-suitable-driver-found-for-jdbcderby-localhost1527 can be of help. – Markus Feb 22 '13 at 18:50
  • 2
    See http://stackoverflow.com/questions/12933113/better-understaning-class-fornamecom-mysql-jdbc-driver-newinstance It answers your question – mortsahl Feb 22 '13 at 18:51
  • Which JRE version are you using? – Vishal K Feb 22 '13 at 19:03
  • if you write your code right, you only need to have it once. break methods down to smaller and smaller tasks. have a method that ONLY handles connecting to the db, then in other areas of your program, simply call that method. – Jeff Hawthorne Feb 22 '13 at 19:18

4 Answers4

1

Here is some very simplified code that illustrates how driver initialization works. There are 3 classes, please put each one in an appropriately-named file.

import java.util.HashMap;
import java.util.Map;

public class DriverMgr {
    private static final Map<String, Class<?>> DRIVER_MAP = new HashMap<String, Class<?>>();

    public static void registerDriver(final String name, final Class<?> cls) {
        DRIVER_MAP.put(name, cls);
    }

    public static Object getDriver(final String name) {
        final Class<?> cls = DRIVER_MAP.get(name);
        if (cls == null) {
            throw new RuntimeException("Driver for " + name + " not found");
        }
        try {
            return cls.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Driver instantiation failed", e);
        }
    }
}

public class MysqlDriver {
    static {
        // hello, I am a static initializer
        DriverMgr.registerDriver("mysql", MysqlDriver.class);
    }

    @Override
    public String toString() {
        return "I am the mysql driver";
    }
}

public class TestProg {
    public static void main(final String... args) {
        try {
            Class.forName("MysqlDriver"); // try with or without this
        } catch (Exception e) {
            throw new RuntimeException("Oops, failed to initialize the driver");
        }
        System.out.println(DriverMgr.getDriver("mysql"));
    }
}

When you call Class.forName, the driver class gets loaded and the static initializer gets executed. That in turn registers the driver class with the driver manager, so that the manager is now aware of it. Obviously, this only needs to be done once.

0

Yes , it's necessary to include every time . but you can use a method for not repeating the codes .

for example

public void connectToMYSQL(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase","username",""password);
}catch(Exception ex)
{
System.out.println(ex.getMessage());
}

}

and before writing any sql statement , just call the method for example

public void insert(String sql)
{
connectToMYSQL();
//.. then do your stuffs 

}
Azad
  • 5,047
  • 20
  • 38
  • 2
    No, it's not necessary to include it every time. When a class is loaded, it's loaded. Reloading it doesn't serve any purpose. And your code example is terrible. It handles exceptions poorly, and doesn't allow getting the connection. – JB Nizet Feb 22 '13 at 19:04
  • I am using it with all may database applications and gives me no exception , am I wrong , if it's please tell me and show me the right way . Thanks – Azad Feb 22 '13 at 19:11
  • The code is legitimate, but unnecessary. You should initialize it once, for example, in your main() method. – skuntsel Feb 22 '13 at 19:45
  • Yes,it's but I don't want to start the connection with the running program . So , it's in general way and again Java is a free-source and every one have it's own way. – Azad Feb 22 '13 at 19:58
  • And you don't need to. But you should want to register database driver on application startup, and not on every database operation. – skuntsel Feb 22 '13 at 20:03
0

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

It must be required to load the driver of database which you are using. the forNmae() method in this line load the driver of mysql database.

Neeraj singh
  • 257
  • 1
  • 8
  • 18
0

The basic idea is that this action forces the driver class to be registered in JDBC's driver manager.

The method Class.forName("fully qualified class name) is used to initialize the static fields of the class and load the JDBC driver class, MySQL driver in your case, to your application. When it is instantiated, it gets registered with the DriverManager. By the latter you create connections, using Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","login","password");, which you later use to query the database.

skuntsel
  • 11,624
  • 11
  • 44
  • 67