I'm trying to create a database file in the parent directory according to my working directory, so far here is what I've done
public void createNewDatabase(String dbName) {
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:..db/" dbName)) {
if (conn != null) {
DatabaseMetaData meta = conn.getMetaData();
System.out.println("The driver name is " meta.getDriverName());
System.out.println("A new database has been created.");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
The problem is, as you can see here try (Connection conn = DriverManager.getConnection("jdbc:sqlite:..db/" dbName))
the DriverManager
is trying to access the directory ../db which doesn't exist.
Have you got any idea how can I achieve that?
CodePudding user response:
Create the db
folder and do this :
DriverManager.getConnection("jdbc:sqlite:../db/" dbName)
Or create a database directly like this :
DriverManager.getConnection("jdbc:sqlite:" dbName)
Try this link.
CodePudding user response:
You can use NIO path to validate the path for the SQLite db connection. Note that toRealPath()
is applied to the parent to ensure the parent dir exists, before resolving the absolute pathname to the database inside the parent directory:
Path dbPath = Path.of("../db/yourdb");
String dbURL = "jdbc:sqlite:" dbPath.getParent().toRealPath().resolve(dbPath.getFileName());
System.out.println("dbURL=" dbURL);
try(Connection conn = DriverManager.getConnection(dbURL)) {
...
or as one liner:
String dbURL = "jdbc:sqlite:" Path.of("../db").toRealPath().resolve("dbName");