Search code examples
javasqlitejdbc

How do establish an JDBC database connection (SQLite) with a relative path independent from any IDE or superior folder structure


I work on a Mac with IntelliJ in a Maven project with SQLite and I've successfully established a connection to the database with a absolute path:

import java.sql.*;
Connection connection = null;
String url = "jdbc:sqlite:/Users/user/any/dir/java_project/database/data.db";
connection DriverManager.getConnection(url);

Which works fine on my PC, but I want the database connection independent of any IDE or superordinate Folder structure, because I work in a team where everybody has a different folder structure (of course) and not uses the same IDE.

The intern folder structure is like that: (IntelliJ generated)

java_project
│  
│
├───src
│   │
│   └───main
│       └───java
│            └─Main.java
│  
│  
└───database
    └─data.db

I've been trying to connect the SQLite file in the Main with a relative path String like:

url = "jdbc:sqlite:../../../database/data.db"

but only the absolute path works. I found that thread: sqlite jdbc Eclipse database relative path

But this person searched for an Eclipse specific solution. Nevertheless,

String url="jdbc:sqlite:"+dbfile.getAbsolutePath()+"\\Demo.db";

looks good, but I don't know, how I import the data.db file to refer to it with the method.

Something else I found was:

connection = DriverManager.getConnection("jdbc:sqlite:"+$PROJECT_DIR$+"/database/data.db");

But IntelliJ couldn't resolve the symbol, I didn't put much effort in making this work because I believe it is IntelliJ specific and I want something which is not depending on an IDE.

The code should run on a server in the future so it would be nice if we had an option to establish a connection with a relative path so it does not matter in which superordinate folder the project is.


Solution

  • Thanks to the kind comment from Mark Rotteveel, I found a solution, which works as I wanted it to:

    import java.sql.Connection;
    Connection connection = DriverManager.getConnection("jdbc:sqlite:"+System.getProperty("user.dir")+"/database/data.db");
    

    That statement is can be anywhere in the file hierarchy as shown in the question.