When handwriting jdbc to operate the database through servlet, ": No suitable driver found for jdbc:mysql://localhost:3306/javaweb” prompt.
No problems were found when checking the database connection, and the experience I searched online was not solved after trying. Then I built a test class locally and wrote the same jdbc code as in the question servlet. The magic is that the query can be executed correctly.
Finally, I spent a lot of time and finally found that there was a problem with the code that executed the registration driver in the tool class.
{
try {
Class.forName("");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
It should have been written in a static code block starting with staticClass loadingexecutes when. I missed static, and the static code block becomes a constructed code block, and the execution time is from class loading to when the object is created. The tool class provides static methods without new objects, and the code of the natural registration driver is not executed, so an error message at the beginning of the article appears.
So a new question is here, why does the wrong tool class not have any problems when used by local test methods?
It turns out that it is from JDBC4.0, and the database registration driver does not need to be explicitly loaded.
Class.forName("");//Register driver can be omitted
- 1
Comments in the class:
/**
* <P>Applications no longer need to explicitly load JDBC drivers using <code>()</code>. Existing programs
* which currently load JDBC drivers using <code>()</code> will continue to work without
* modification.
* /
- 1
- 2
- 3
- 4
- 5
When obtaining the connection, the appropriate driver class will be automatically found and the class currently using the same driver will be initialized without manual registration.
Therefore, in the local test method, it is possible to execute normally without registration.
As for whyjavaweb projectDriver registration cannot be omitted, and I haven't figured it out yet.