Search code examples
javamysqljdbcjava-module

Jar in external libraries but cannot import in code


(more info at bottom)

I am using Maven to fetch the MySQL Connector for java

dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

As such, it shows up in my External Libraries (intellij)

screenshot of external libraries (intellij)

However, in my code, I cannot import java.sql.*, as java.sql is not an option.

screenshot of failed java.sql import

In addition, I have made sure that my Project Structure is correct, having the dependency set as Compile scope

screenshot of project structure

I have also invalidated cache.

I have been stuck on this issue for a bit and cannot find a resolution; any help is appreciated.

More info: java.sql Works in java 8 projects Works in blank java 12 projects (not created with openjfx 12 archetype)

Inside main I now have this line of code:

java.sql.Connection c = null;

The error message I get when running is:

Error:(37, 9) java: package java.sql is not visible
  (package java.sql is declared in module java.sql, but module com.github.phaserush does not read it)

Solution

  • The error indicates you are using the Java module system, and the java.sql module (containing packages java.sql and javax.sql) is not part of the default set of modules loaded by Java. You will need to explicitly depend on it.

    In your src/main/java edit your module-info.java and add requires java.sql;. For example:

    module com.github.phaserush {
        requires java.sql;
    }
    

    Where com.github.phaserush is your module name based on the exception message in your question.