6

I'm creating a web app using servlets and Tomcat in IntelliJ. I want to connect my application to a MySQL database with JDBC. I downloaded MySQL Workbench, connected to it, and created a database.

Now, in my IntelliJ project I followed this tutorial to add database connection, and my properties look like this: enter image description here

My mysql driver version is 5.1.35, so it should be compatible with JDBC 4.0. As found out (mainly here) to connect with my database I should use just:

Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);

However,when I try to connect I get No suitable driver exception. Even when I add

Class.forName(DB_DRIVER).newInstance();

I end up with the same. It only works when I add manually jar to this driver in my libraries and artifacts: enter image description here enter image description here

Is it really the only way? If IntelliJ downloaded the jar automatically, shouldn't it also load it automatically when I try to connect? In DriverManager documentation there is something like this: As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. Do I have to configure this property somehow?

3

1 Answer 1

6

Short answer - Yes, project driver jars need to be mentioned explicitly.

When you configure DB for Intellij (using its database panel), Intellij can download respective driver based on database type. This is similar to configuring MySQL Workbench. Its for development purposes.

When you use JDBC connection within your project, you need to tell Intellij somehow that you need corresponding driver. You can do it the following ways:

  1. Manually add driver jar as library to the project (like you did)
  2. In code, use the driver class. Use Intellisense to import the JAR (screenshot below). 'add to classpath'.
  3. Same as above but for maven based project (screenshot below). 'Add maven dependency'
  4. Use Spring-boot framework, let it automatically figure out the driver for you.

enter image description here enter image description here

2
  • thanks for your answer. Does any of your solutions uses this loading drivers during DriverManager initialization that I've mentioned in my question?
    – Mohru
    Commented Jan 16, 2017 at 23:08
  • Doing DriverManager initialisation in code requires Class.forName("class_name_string"). Intellij will not load class because its a string. Thus, just for import, write the driver class name (with package) anywhere in your code, and then use intellij suggestions to import the JAR. Once imported, remove that class name code.
    – DeepakV
    Commented Jan 17, 2017 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.