Connect to a SQlite file inside a .jar file with JDBC? [duplicate] - java

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

Related

write to sqlite db packaged inside a jar

I'm trying to use a DB for reading and writing that is contained in a JAR.
I can read in it, but can't write throwed exeception :
java.sql.SQLException: path to '/database/scddata.db': 'LocationOfJar/database' does not exist
Is there any way I can bundle the database file inside a JAR?
Thanks in advance.
Jar files does not allows to write.
So :
define a working path (in properties for example). Let's call it : workingPath/file.db.
on init of your program, before opening your db.
check if db exists in working path
if does not exists : copy your jar file.db file to workingPath/file.db .
Then you program will use the db from workingPath/file.db for execution.

Where should I put other components (like .mdb) in Netbeans project

I am new in Netbeans, I am doing project which is manipulate with MS Access Database (.mdb or .accdb).
Inside my code, I need to write the whole directory of my database file in order to connect it, like:
conn = DriverManager.getConnection("jdbc:ucanaccess://D:/abc/def/db.accdb");
Which folder should I put my database file in so that I no need to write the whole directory to connect it, like: conn = DriverManager.getConnection("jdbc:ucanaccess://db.accdb");?
You do not want to hardcode a database path in your code: good point!
Unfortunately, it looks like UCanAccess offers no special folder to automagically find the database: it just tries to find it where it is declared. So if you use a relative path, it will rely on Java processing and Javadoc for File class says:
By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
If you use shortlinks under window, you can specify a start directory in the shortlink, but I would not rely on it because it is not a common usage even on Windows.
So the correct way (and common usage) is to use an environment variable. This variable would contain the database fullpath if you have no other external configuration value, or it will contain the path of a property file that in turn contains other configuration values.

Access WebContent folder file in java class

I'm developing a web application with sqlite database. While developing the application, I created the database connection in a java class. There I've mentioned my url as like below
String url = "jdbc:sqlite:D:\\Database\\profileDB.db";
I want to place the db file from that location to specific location inside my Webcontent folder say resources.
Now I want to change my URL pointing to folder file.
Webcontent/resources/profileDB.db
.
Anyone kindly suggest me how to do this. For the information, I'm not using any servlet in creating the connection, it is just a normal java class.
I dont know about the SQLite database but if you just want the url to the db file the you can use getResource("name_of _the resource") method of the Class class. it gives you the URL of the named resource. the rules for searching for the resource depends upon the classloader used to load the class.
for eg : my package(folder) structure is :
test-
|-foo.class
|-image.png
then inside foo.class
URL url = getClass().getResource("image.png");
it will give the url to the image.png
IMHO, you need to add sqlite.jar in Project Properties -> Java Build Path -> Libraries -> Add External Jar.
Then you can try connecting using:
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("JDBC:sqlite:sample.db");
} catch (Exception e) {
e.printStackTrace();
}
You can refer this link for sqlite jdbc

Package and use embedded database (H2.db file) inside a Jar?

I'm using H2 embedded database for my application. I would like to contain everything the application needs in it's own Jar, including it's database if possible. My app does not need to create temp files or anything, so basically the user just runs the Jar.
Is it possible to embed a database inside a Jar, and be able to INSERT new records as well as just SELECT out?
EDIT: Just to clarify, I'm not looking to embed the H2 driver jar inside my distributable jar, I'm looking to embed the h2 database file (someDatabase.h2.db file) inside a Jar and still be able to write/read from that database.
If you wish to embed the myDatabase.h2.db file inside the .jar, you can do so, but you'll have read-only access to the database. As .jar files are read-only, you can't modify them and therefore can't execute INSERT, DELETE or any DDL command.
That being said, below is an explanation on how to embed it read-only.
According to H2's documentation:
The JDBC URL "jdbc:h2:~/myDatabase" tells the H2 Engine to look for a database file named myDatabase.h2.db in the home directory of the current user.
The JDBC URL "jdbc:h2:file:/myDatabase" tells the H2 Engine to look for a database file named myDatabase.h2.db in the current directory (where the java program was executed).
If you embed the h2.db file inside a .jar, it is not accessible in a plain way. It is only accessible as a file inside a zip file.
In order to make H2 uset it, you have to use a zip as URL:
jdbc:h2:zip:~/data.zip!/test
See more in "Read Only Databases in Zip or Jar File".
When you embed the file as a resource in the jar, you may get it's relative url. Using...
MyClass.class.getClassLoader().getResource("myDatabase.h2.db")
...you'll get something like:
jar:file:/C:/folder1/folder2/myJar.jar!/myDatabase.h2.db
You can then manipulate it as a String and pass as JDBC URL connection to H2.

database connectivity?

How to establish SQL 2005 database connectivity with Java application. Actually I don't know how to set path for JDBC. Any help would be great.
Download the jdbc driver from http://www.microsoft.com/sqlserver/2005/en/us/java-database-connectivity.aspx.
You can either download the Windows or Unix version. It does not really matter which one you use.
If you chosed the Windows version, run the downloaded exe file; this will create a directory called Microsoft SQL Server 2005 JDBC Driver in the directory you downloaded the file to.
Add the file Microsoft SQL Server 2005 JDBC Driver\sqljdbc_1.2\enu\sqljdbc.jar to your classpath (either using the -cp option of java or, if you are using an application server, by putting it in the appropriate directory).
Set your connection. Basically, the information required for this are:
the driver class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
the connection url: jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
Check Connecting to SQL Server with the JDBC Driver for more details and/or the resources available in the help directory (sample code available in help/samples/connections/ConnectURL.java).
This is a HOWTO from Microsoft on where to get the driver and how to configure it.
Briefly, download the .jar from Microsoft, reference it in your classpath and use:
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;user=MyUserName;password=*****;";
Connection con = DriverManager.getConnection(connectionUrl);
substituting the relevant info.
This link will help you with this
jdbc connection mssql
Code Snippet
private java.sql.Connection getConnection(){
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
Your actual problem is thus that you don't know what to do with the phenomenon "classpath".
Actually, the classpath is kind of a collection of disk file system paths which points to the whole .jar file(s) and/or to some root folder with .class file(s) where the Java Virtual Machine should lookup for classes to be imported and loaded.
You can specify the classpath during compile and runtime using the -classpath or -cp argument of javac.exe and java.exe. The -cp is just a shorthand, it does nothing different. Then you have the mysterious %CLASSPATH% environment variable which you should just entirely forget. It is a poor thing which was intented to make starters easy to manage the classpath, but at end it just confused them more.
As you're using Class#forName() to load the driver, you only need to have it in the classpath during runtime, not during compiletime. So here's a basic example how to execute it:
java -cp .;c:/path/to/mssql-jdbc-driver.jar com.example.YourClass
You see, the classpath exist of two parts, the . which represents the current working directory and the c:/path/to/mssql-jdbc-driver.jar which should be the absolute path to the JAR file. The ; is just a path separator (in Windows; in Unix and clones it should be a colon :). Note: if a path contains spaces, e.g. c:/spacy path to/file.jar, then you need to wrap the individual path with doublequotes.
If you're using an IDE such as Eclipse, then normal practice is that you create a folder in the project where in you can drop all of those 3rd party JAR files which are required by the project. Create a project folder called lib, drop the JDBC driver in there and rightclick project > Properties > Java Build Path > Libraries > Add JARs > Select the JAR file which you dropped in project's lib > OK.
That should be it. Hope this helps.

Categories