Julian
Julian

Reputation: 3859

Set path to a jdbc SQLite database, where it will be located

I am using the following script to connect to a local SQLite database in Java:

public static Connection createOrOpenDatabase(String database) {

        String url = "jdbc:sqlite:" + database;

        try {
            Connection conn = DriverManager.getConnection(url);
            return conn;
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

So this works pretty good and it saves it in the same directory, where also the jar is located. Now is my question, how can I set a absolute path, where the database is located.

For example the current location of the db file is:

C:\MyProjects\JavaFXProject\app\dist\main.db

Now I want to save this file to the user.home directory:

C:\Users\Julian\MyProjects\JavaFXProject\main.db

How can I achieve this?

Upvotes: 0

Views: 5400

Answers (3)

GreenMarty
GreenMarty

Reputation: 382

OP asked for absolute path for user.home which is relative path. So I add OS independent answer for accessing user.home path since other answers cover only hard-coded path or jar's sub-dir.

...how can I set a absolute path, where the database is located.

and

Now I want to save this file to the user.home directory:

C:\Users\Julian\MyProjects\JavaFXProject\main.db

How can I achieve this?

To get relative path to current active user home directory, we gotta ask Java two information then combine them into a correct path:

  1. User.home location.
 String userHome = System.getProperty("user.home");
  1. Current OS path separator.
char separator = File.separatorChar;
  1. we just combine them into String url;
String url = "jdbc:sqlite:" + userHome + separator + "MyProjects" +separator + "JavaFXProject" + separator + "main.db"

Now the url is pointing to the given sub-directory inside user.home (Windows / Linux regardless).

Upvotes: 0

ahmed rashid
ahmed rashid

Reputation: 1

first, make sub folder in src in your project and make sure you make it in your text editor - like eclipse or netbeans

this is for making sub folder in the project

enter image description here

then you can add your path

Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:src/database/school.db");

this is for connection code is your custom path

enter image description here

Upvotes: 0

Gord Thompson
Gord Thompson

Reputation: 123419

how can I set a[n] absolute path

You can just include it as part of the connection URL, e.g.,

jdbc:sqlite:C:/Users/Julian/MyProjects/JavaFXProject/main.db

Upvotes: 1

Related Questions