How to set the jdbc URL for H2 database? - java

When I try to do the flyway tutorial for Java, I wanted to check the flyway_schema_history table stored in the embedded H2 database. The database file (foobar.mv.db) is created at project target folder with the configuration
<url>jdbc:h2:file:./target/foobar</url>
But I cannot open the database from browser (localhost:8082). I had to copy the database file to my user home dir because that's the default location that H2 console uses. How should I specify the jdbc URL in order to have the console pointing to the project target folder? The default URL is jdbc"h2:file:~/foobar. I want to know how to make it point to my project, say at C:\Users\scong\IdeaProjects\my-flyway-migration-service. foobar.mv.db file is created at C:\Users\scong\IdeaProjects\my-flyway-migration-service\target with above configuration.
The answer in the post What is the jdbc connection string for h2 database? actually doesn't work for me. The console complains the colon character after the drive letter (C:) in the path. I tried to use the below absolute path,
jdbc:h2:file://localhost/C:/Users/scong/IdeaProjects/my-flyway-migration-service/target/foobar
It gave the below error
General error: "java.nio.file.InvalidPathException: Illegal character [:] in path at index 13: //localhost/C:/Users/scong/IdeaProjects/my-flyway-migration-service/target/foobar" [50000-214] HY000/50000 (Help)

Related

database location in IDE

1- In Netbeans , this JDBC_URL works fine (using stand alone embedded Derby ):-
someApp (this is the directory)
|
src
|
dataBasePackage.myDB
mainPackage
|
MainClass.java
JDBC_URL= “jdbc:derby:src/dataBasePackage/myDB”;
2- A folder on local machine name : “appFolder” contains following :
appFolder image
the .exe works fine and app starts...BUT user can’t connect to myDB ...which means JDBC_URL is wrong.
my question: When I want repackage the someApp to get a someApp.jar, I have to change the JDBC_URL to match the “appFolder” ; I tried multiple combinations,none worked !!
P.S:
setting myDB on “file system” like JDBC_URL=” jdbc:derby:myDB “ ...also not work though with different arrangement .
You control the location of your database folder via your JDBC Connection URL, and via the specification of the Derby "system home".
Both these concepts are clearly explained in the Derby documentation. To read about that, start here: https://builds.apache.org/job/Derby-docs/lastSuccessfulBuild/artifact/trunk/out/devguide/cdevdvlp34964.html
The location can be specified in a relative or absolute fashion.
If you give an absolute database name in the Connection URL, the database is located at the name you specify. Since it is absolute, it doesn't depend on the Derby system home.
If you give a relative database name in the Connection URL, the database is located relative to Derby's system home: http://db.apache.org/derby/docs/10.11/ref/rrefproper32066.html

Eclipse: Export JAR with SQLite Database [duplicate]

I have the following question which is keeping me busy for some time now.
I am building a Java project in Netbeans and I have an embedded sqlite DB which I use in this project.
Currently the DB is located in the package src/release/.
I reference the db from the code the following way:
c = DriverManager.getConnection("jdbc:sqlite:src/release/db.db3");
When I run the project from within Netbeans it works without any problem. But when I try to build it and run the created jar-file (in the dist-folder).
I get the following error message (translated from Dutch description):
Opening connection failed: path to
scr/release/db.db3:'C:\users\idxxxxx\Documents\\dist\src'
does not exist
When referencing the DB in the code like this:
c = driverManager.getConnection("jdbc:sqlite:db.db3");
and adding the db-file to the root of the output-dir (so not in the jar itself), the application works partly, but some db-data is missing in my application (empty comboboxes).
So there seems to be an issue also.
My question is:
How can I add an embedded db - sqlite in this case - in netbeans to my project so it will be part of my project?
Where should I put the db-file and how do I reference it from within my project-code?
I don't want the enduser to see any db-file in the file(s) he will receive.
so I would like the db-file to be part of the .jar if possible.
Tnx
SQLite needs separate files, even without the need to update the database.
Need ensures locking and ensures database ACID properties.
SQLite from inside .jar
SQLite is designed to work with direct file access.
SQLite may require additional privileges not available in some environments.
The SQLite data files could be extracted from the JAR to a temporary location at start.
It is not a good choice to write the database url, directly into the program.
getConnection("jdbc:sqlite:src/release/db.db3");
Let your application look for the file. If not found: error: File db.db3 not found message. Then know the user, not the program is going wrong, but it is missing the database file.
Since you are working with java, it is easy to create dynamic url.
e.g. "jdbc:sqlite:"+PathToApp +"/data/db.db3".
Then the application knows where to copy the extracted file (db.db3 from the jar ) .
extract SQlite from .jar
You can let java doing it for you.
Use jdbc:sqlite::resource:
you need the sqlite-jdbc JAR, so extract the JAR file and add into the application JAR.
DB files will be extracted to a temporary folder System.getProperty(“java.io.tmpdir”).
e.g.
[...]
import org.sql.*;
import org.sqlite.*;
[...]
try {
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
config.enableFullSync(true);
config.setReadOnly(false);
SQLiteDataSource ds = new SQLiteDataSource(config);
ds.setUrl("jdbc:sqlite::resource:"+
getClass().getResource("db.db3").toString());
conn = ds.getConnection();
}catch(SQLException se)
{
System.out.println("SQLError: "...");
}
Update oct. 2014
org.sqlite SQLiteConfig + SQLiteDataSource
2014 October 8th: sqlite-jdbc-3.8.6.jar Updated to sqlite 3.8.6

Where is the H2 database stored?

I am trying to use an H2 database with Java. I cannot seem to find out where the data is being written.
The database URL I am giving is: jdbc:h2:/db/bh.
I am connecting with the database using Java like so:
dbObj.setDBConnection(DriverManager.getConnection(hObj.getDBUrl(), hObj.getDBUsername(), hObj.getDBPassword()));
where DB URL is given above.
Username: sa
Password: (empty).
I am running the jar from within the following folder:
C:\work\sampleH2\sampleH2.jar
My understanding of the FAQ section of H2 says that the database bh will be found in the folder db/ of the folder sampleH2. But that is not the case. Where can I find it?
according to http://www.h2database.com/html/cheatSheet.html there is a difference between storing in:
relative path (somewhere under current directory): jdbc:h2:test
absolute path (somewhere under root directory): jdbc:h2:/data/test
so i would look for it on your main drive (probably c:) under path you specified

H2 Database Java Servlet Connection Path issue

Lately I have been looking into having a servlet with a local database. With a bit of research I found H2 Database Engine (Wikipedia). This is perfect for what I want but I am having trouble with the local path for my servlet.
Example:
I need to create the H2 Database in my WebContent folder so its apart of the project. However I cannot seem to get the code right to localise it.
Example CODE: - H2.Jar - Connection String to SQL Database
String url = "jdbc:h2:"+request.getContextPath()+"/emailDB;IFEXISTS=TRUE";
Class.forName("org.h2.Driver");
Connection conn = DriverManager.
getConnection(url, "adminuser", "pass");
Example CODE (ERROR): - H2.Jar - Connection String to SQL Database (OUTPUT)
org.h2.jdbc.JdbcSQLException: Database "C:/emailservlet/emailDB" not found [90013-174]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:332)
at org.h2.message.DbException.get(DbException.java:172)
at org.h2.message.DbException.get(DbException.java:149)
at org.h2.engine.Engine.openSession(Engine.java:54)
at org.h2.engine.Engine.openSession(Engine.java:160)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:139)
at org.h2.engine.Engine.createSession(Engine.java:122)
at org.h2.engine.Engine.createSession(Engine.java:28)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:323)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:105)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:90)
at org.h2.Driver.connect(Driver.java:73)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at emailservlet.msdbcon(emailservlet.java:540)
As you can see the issue i am getting is that even though im requesting the contextpath i am still getting C:/ written before.
If you can help me figure out the error in my code that would be so helpful!
Thank you in advance!
The driver expects file system path where it can create files. It's converting the relative path to absolute by using root directory that is your C: drive. To get absolute path to WebContent folder you need to use ServletContext#getRealPath()
Also it's not a good idea to store H2 file's in WebContent folder you should store them in WEB-INF folder so that its not accessible to users.
Below is how the url should be formed
String path = getServletContext().getRealPath("/") + "/WEB-INF";
String url = "jdbc:h2:"+path+"/emailDB;IFEXISTS=TRUE";
This will create H2 files in WEB-INF folder.
Considerations taken from the Features page on H2Database.com site:
The database URL for connecting to a local database is jdbc:h2:[file:][] . The prefix file: is optional. If no or only a relative path is used, then the current working directory is used as a starting point.
The case sensitivity of the path and database name depend on the operating system, however it is recommended to use lowercase letters only.
The database name must be at least three characters long (a limitation of File.createTempFile).
The database name must not contain a semicolon.
To point to the user home directory, use ~/, as in: jdbc:h2:~/test.

How to include SQLite database in executable Jar?

I have created a Swing application that uses SQLite as a local database. The database file is located in project's root directory.
Project/DatabaseFile
The application runs fine on Eclipse, but when I run the packaged executable Jar, I get the following error:
No such table : table1
This means that the database is not reachable. When I examined the contents of the resulting JAR file, the database file was not there anymore.
In the code, I've linked the database as follows:
jdbc:sqlite:DatabaseFile
My question is, how to include the SQLite database in the executable Jar?
EDIT
When I placed the DB file in the source Folder Project/src/DatabaseFile and changed the path to jdbc:sqlite:src/DatabaseFile, it worked on Eclipse but again when running the Jar file as java -jar Project.jar. It said:
path to 'src/DatabaseFile': 'C:\Users\name\src' does not exist
I think I need to specify a relative path for the database.
EDIT
This is how I connect to the database:
public Connection getConnection(){
try{
Class.forName("org.sqlite.JDBC").newInstance();
con = DriverManager.getConnection("jdbc:sqlite:src/DatabaseFile");
} catch (Exception e) {
Log.fatal("Méthode: getConnection() | Class : SQLiteConnection | msg system : " + e.getMessage());
}
return con;
}
What library are you using for SQLite?
I did a search based on the connection URI you indicated and found this one. In the documentation it says:
2009 May 19th: sqlite-jdbc-3.6.14.1 released. This version supports "jdbc:sqlite::resource:" syntax to access read-only DB files contained in JAR archives, or external resources specified via URL, local files address etc. (see also the detailes)
If that is the driver you are using, then I would suggest the following connection URI:
"jdbc:sqlite::resource:DatabaseFile"
The key is that since your database is in a jar file, it can not be access as a file with FileInputStream. Instead it must be accessed through the JVM's support for it (namely with Class.getResource() or Class.getResourceAsStream()). Do note that resources contained within jar files are read-only. You won't be able to save any changes to your database.
I have found two different ways to name the filepath depending on how you are trying to access it. Assuming you are accessing the db is located in /yourproject/resource/ or /yourproject/bin/resource ( havent narrowed it down, mine is in both and I'm happy with it) you should use this as your path:
//Eclipse test path
String url = "jdbc:sqlite:resource/mydb.db";
or
//runnable jar path
String url = "jdbc:sqlite::resource:mydb.db";
then
mysqlitedatasource.setUrl(url);
Your way also works... by putting the db in /src

Categories

Resources