how can i use derby database with the build .jar file? - java

i'm using java with the derby database.
When i start the connection of the "jdbc:derby"-database in netbeans and run my code,the program shows up and everything works fine.
By opening the built ".jar"-file, the program just shows up and close immediately right after that.
So how do i have to configurate netbeans that the build .jar file work with the derby database?
(i thought derby was file based, so that the build process must generate something like a database file)

If your program crashes during the execution of your jar file, there is probably an exception. If it works in Netbeans, the exception is probably caused by the path to your derby.jar.
The first thing I can think of is that you have incluced the derby.jar in your application using a relative path and you have not moved the derby.jar inside your project library.
Try to do the following:
1: copy the derby.jar to a directory (for example /lib) in your project folder
2: include the jar using relative path from your /lib folder
EDIT:
Here is a sample code of how to create your database when it is newly created:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection con = DriverManager.getConnection("jdbc:derby:C:\\Users\\TheReaver\\MyDB;create=true;user=thereaver;password=12345");
PreparedStatement st = con.prepareStatement("SELECT ID, NAME FROM APP.TABLE1");
try
{
ResultSet res = st.executeQuery();
}
catch(SQLException e) {
//if table not found, then create all tables
st.executeQuery("CREATE TABLE TABLE1(ID int, NAME varchar(20)))");
//execute all statements that create your database
//or execute an sql file that stores all your queries
}

Related

ClassNotFound & No Suitable Driver, where did I go wrong?

I have created a program that works perfectly in the IDE on NetBeans, but anytime I build the .jar file, the database connection stops working. I've already added the CLASSPATH to the MySQL Connector, as well as defined Class.forName("com.mysql.jdbc.Driver"); Still nothing..
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/gearheads";
Connection conn = DriverManager.getConnection(url,"root","HellOnEarth202021");
Statement stmt = conn.createStatement();
ResultSet rs;
String pid = txt_staffID.getText();
rs = stmt.executeQuery("SELECT name,timeraccess FROM staff WHERE staffid = '"+pid+"'");
while ( rs.next() ) {
String timeraccess = rs.getString("timeraccess");
String staffName = rs.getString("name");
getLogin = staffName;
System.out.println(staffName);
System.out.println("Users Admin Level: " + timeraccess);
if ( timeraccess.equals("1")) {
this.dispose();
new menu().setVisible(true);
System.out.println("Access Granted");
}else
System.out.println("Access Restricted.");
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
txt_staffID.setText(e.toString());
System.err.println(e.getMessage());
}
This, as it stands, outputs:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Where taking out the Class.forName outputs:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/gearheads
Please help me. This link is a screenshot of my libraries.
My Libraries:
If its runnning correctly inside Netbeans, then the MySQL driver is correct.
You have to search for Manifest file (MANIFEST.MF) and probably will have to unjar the contents of the driver inside your own JAR file.
I'll leave this answer by now, but will try to gather the details to bring it back here.
I also use NetBeans and when I generate the JAR file, its already copying the dependant libraries and generating the correct MANIFEST.MF.
I ended up with the following structure
MyProject\dist\lib\JdbcDriver.jar
and
MyProject\dist\MyProject.jar
Inside MyProject.jar, I have the following MANIFEST.MF:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.7
Created-By: 1.8.0_201-b09 (Oracle Corporation)
Class-Path: lib/JdbcDriver.jar
X-COMMENT: Main-Class will be added automatically by build
Main-Class: myproject.MyMainClass
Please, verify with you are copying the lib folder altogether with your JAR file.
Just to leave here the final solution (#Nick Media final comment): you have to check "Copy Dependent Libraries" in Build>Packaging Project Properties.
It is not clear exactly what you are doing wrong, but you are clearly doing something incorrectly:
It is often better to use DriverManager.getConnection rather than Class.forName and a specific driver class name. This is the approach recommended by the Oracle Java Tutorial; see https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
If you are loading the driver via its classname, use com.mysql.jdbc.Driver with MySQL Connector/J 5.x and com.mysql.cj.jdbc.Driver with MySQL Connector/J 8.x.
If this is a webapp, make sure that the relevant driver JAR file is actually in your WAR file, and/or that it is being deployed correctly.
If this is a command line app, make sure that you include the driver JAR on the runtime classpath. (Especially if you are trying to run it outside of your IDE.) Alternatively, consider creating a shaded JAR that included all of the apps dependencies. (It is a bit hard to advise since you haven't told us if you are using a build tool like Ant, Maven, Gradle, etc.)
The driver doesn't actually need to be a compile time dependency, though there is little harm in doing that. (The harm is that you might accidentally add imports to the MySQL implementation classes to your app ... and run into problems.)

JAVA Runnable .JAR File incomplete execution. Eclipse IDE Runs to completion

Running into an issue with a JAVA application that I'm hoping someone can provide some clarity to. I have a simple Java Application which is being built in the Eclipse IDE. I have JRE 1.8.0_251 installed on PATH.
My application at a basic level performs the following:
Load a properties file
Connect to a MSSQL Database based on that SQL File (using java.sql.Connection)
Queries some data.
Updates some data.
This all works without issue in Eclipse. However, when I export my file to a runnable .JAR file, it appears to stop after attempting to initialize the database connection. However, it does not throw a SQLException and never returns from the method. I checked my .jar file in 7ZIP to make sure that the SQLJDBC42.jar was packaged in the folder and it was.
The last log line I see when my runnable JAR executes is: Log.info("Connecting to Database...") however, all items run / and are logged in Eclipse execution.
Any ideas? Code below:
public void ConnectDatabase() {
Log.info("Connecting to Database...");
try {
//Connect to Database and Log success.
ConnectionInstance = DriverManager.getConnection(connectionURL);
Log.info("Database Connection Successful.");
} catch (Exception e) {
Log.info(String.format("ERROR | DATABASE: %s", e));
//System.exit(0);
}
Log.info("Leaving Database Method.");
}

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

Adding embedded sqlite-db to Netbeans project

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

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