Reputation: 3859
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
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:
String userHome = System.getProperty("user.home");
char separator = File.separatorChar;
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
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
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
Upvotes: 0
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