Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Class.forName, JDBC connection loading driver [duplicate]

Tags:

java

mysql

jdbc

While doing a simple JDBC connection, all the resources gives the same code that

String driver = "com.mysql.jdbc.Driver";
Statement statement = null; 
Class.forName(driver); 
Connection conn  = DriverManager.getConnection(url + dbName,userName, password);

But we actually nothing do with "Class.forName(driver)". We didn't stored it anywhere. What is the use of that as we nothing do with Class.forName(driver)'s return.

like image 692
Selvaraj Avatar asked Dec 25 '22 23:12

Selvaraj


1 Answers

Class.forName() attempts to load the named class. In early versions of JDBC, this was necessary as the Driver class required the class to be loaded in this way. This hasn't been required for ages.

Leave out the call and nothing bad will happen.

For some reason, tutorials and examples persist with the old way.

The only tiny benefit of loading the class manually is that it tells you exactly what the problem is in case you haven't got the right class in the classpath.

like image 83
Bohemian Avatar answered Mar 03 '23 00:03

Bohemian