3

I'm having a little problem making simple CRUD application in JavaFX using Maven and H2 Database. I've created a database (which .db file is located at Users direction by default) and I've problem with connected my Java project with this file. My database file (data.mv.db) is located in default directory so URL of JBDC is absolutely correct.

It looks like the DBConnection class isn't seeing my .db file, I don't know why.

When I'm running a DBConnection class IDE's putting out SQLException:

java.sql.SQLException: No suitable driver found for jdbc:h2:~/data

Here is my DBConnection class code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:h2:~/data";
        String username = "sa";
        String password = "123";

        try {
            Connection connection = DriverManager.getConnection(jdbcURL, username, password);
            System.out.println("Connected to H2 embedded database.");

            connection.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

H2 Database library is added to my project by dependency in Maven. Here is dependency in pom.xml file:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.2.220</version>
    <scope>test</scope>
</dependency>
Damian L
  • 29
  • 5

1 Answers1

3

Your dependency is for test scope, so it is not added to the runtime classpath.

You need to change it to runtime. Change <scope>test</scope> to <scope>runtime</scope>.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.2.220</version>
    <scope>runtime</scope>
</dependency>

The scope element can be omitted if it is a compile dependency, because the scope defaults to that. However, if that's the case, the error would be a compile time and not at runtime.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.2.220</version>
</dependency>

See also:

Andrés Alcarraz
  • 1,570
  • 1
  • 12
  • 21
  • 2
    @DamianL Note if you have a dependency you need to reference directly in your main code (i.e., the code under `src/main/java`), then the idiomatic approach is to omit the `` element entirely and let it default to `compile`. However, since all JDBC drivers are [service providers](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/ServiceLoader.html) for `java.sql.Driver`, using `runtime` can work in this case. – Slaw Aug 18 '23 at 14:50
  • @Slaw, Thing is, the OP has a runtime problem not a compile time problem, the dependency is at runtime, that's why I explicitly put `runtime` as scope. – Andrés Alcarraz Aug 21 '23 at 16:23
  • 1
    Yes. I wasn't correcting you, I was providing more information to the OP. – Slaw Aug 21 '23 at 17:02