I start learning java and this is my first project in java, I tried every StackOverflow answer I could find but it didn't work in my case.
in my project I was required to work whit derbyDB, I run the project in IntelliJ investment and the DB connection work. The problem start when I create a jar file for my project. When I try to run the jar file I get this exception: 'java.sql.SQLException: No suitable driver found for jdbc:derby:C\CostManagerDB'
I try with and without:
- Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
- Add java.sql.Driver file to src\META-INF\services, file content: org.apache.derby.jdbc.EmbeddedDriver
- Add modules->dependencies: derby.jar. derbynet.jar, derbyclient.jar, derbytool.jar
My project ended when it try to create a connection, how I can fix that?
My code
import java.sql.*;
public class CostManagerDB {
// Check if the database exists if not create local database
public CostManagerDB() throws Exception{
// Check if the database exists
try {
Connection conn;
// Register the DerbyDB JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
// Establish a connection to the database
conn = DriverManager.getConnection("jdbc:derby:C:\\CostManagerDB");
conn.close();
}// Create the database if not exists
catch (SQLException e) {
// Check if the exception is database not found
if(e.getSQLState().startsWith("XJ")){
CreateDB();
}
else { throw e; }
}
}
/* Create a local database for the program whit 2 tables (Expenses, Categories) and add initial data */
public void CreateDB() throws SQLException{
// Create the database
Connection conn = DriverManager.getConnection("jdbc:derby:C:\\CostManagerDB;create=true");
// Execute a SQL statement to create a new tables
Statement stmt = conn.createStatement();
// Create a categories table
String createCategories = "CREATE TABLE Categories (Id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY " +
"(START WITH 1, INCREMENT BY 1), CategoryName VARCHAR(50))";
stmt.executeUpdate(createCategories);
// Insert to categories table
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Categories (CategoryName) VALUES (?)");
pstmt.setString(1, "Grocery");
pstmt.addBatch();
pstmt.setString(1, "Books");
pstmt.addBatch();
pstmt.setString(1, "Clothing");
pstmt.addBatch();
pstmt.setString(1, "Electronics");
pstmt.addBatch();
pstmt.setString(1, "Bills");
pstmt.addBatch();
pstmt.setString(1, "Entertainment");
pstmt.addBatch();
pstmt.executeBatch();
// Create a expenses table
String createExpenses = "CREATE TABLE Expenses (Id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY " +
"(START WITH 1, INCREMENT BY 1),Amount FLOAT, Category VARCHAR(50), Currency VARCHAR(20), " +
"Description VARCHAR(100),Date DATE)";
stmt.executeUpdate(createExpenses);
// Close the statements and connection
pstmt.close();
stmt.close();
conn.close();
}
}