问题
I've requirement to create database once with create/insert statements and then make it available inside javafx runnable jar with read only DB access.
I just gone through H2 database document many time and tried to achieve this using H2 Driver version 1.4.196 and 1.4.192 but I think I'm missing something.
I can connect without including it into runnable jar and read only things works as well. But I need to access it from jar itself to prevent DB access from outsiders.
Can I've connection string or logic to connect read only DB file from jar itself ?
Ofcourse I need more clear practical example from this, this and this.
I've implemented zipping logic as this and it works fine from given path.
But when I've added zip file in runnable jar and accessing it through following code:
DriverManager.getConnection("jdbc:h2:file:split:zip:./test.zip!/test");
Then it throws exception with:
Exception in thread "main" org.h2.jdbc.JdbcSQLException: IO Exception: "java.io.FileNotFoundException: .\jar\res\buzdirectory.zip (The system cannot find the path specified)"; "listFiles zip:./jar/res/buzdirectory.zip!/" [90031-196]
If I put fully qualified path then it works well:
DriverManager.getConnection("jdbc:h2:file:split:zip:C:\\CoreJava\\src\\main\\java\\res\\test.zip!/test");
What I'm missing here to access it from jar file.
回答1:
I think we cannot open the database file directly from the runnable JAR file. To access it should be a "real" file, so we will need to extract it from the JAR and then open that copy.
For example, to extract the database from the JAR into a temporary file:
File dbFile = File.createTempFile("temp", ".zip");
dbFile.deleteOnExit();
java.nio.file.Files.copy(this.getClass().getResourceAsStream("/db/temp.zip"),
dbFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
StringBuffer connStr = new StringBuffer("jdbc:h2:file:split:zip:")
.append(dbFile.getAbsolutePath()).append("!/temp");
Connection conn = DriverManager.getConnection(connStr.toString());
conn.close();
System.out.println("closed");
By the way this is not preferable approach yet all. But we can use this kind of approach in some special cases.
来源:https://stackoverflow.com/questions/49352706/how-can-i-connect-to-read-only-h2-database-file-which-is-inside-runnable-jar