问题
I am trying to access a database that is stored in the classpath. I have installed ucanaccess 3.0.0 and all the required .jars.
My project hierarchy:
:
Here is the code I have so far:
public void login()
{
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:ucanaccess:/database/theDB.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT Student_Number FROM User");
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It's a simple login screen and I'm just testing the connection to the databse on a button click. I understand that referencing an absolute file-path is not good, so I thought having the file in the classpath would be better.
I am getting the error
No suitable driver found for jdbc:ucanaccess:file:/C:/Users/Gandalf/workspace/FubbleApp/bin/database/theDB.accdb
So I think it must be the "/database/theDB.accdb" but I am not sure how to fix this issue.
Any help is appreciated. Thanks in advance
回答1:
The path to the database file (.accdb or .mdb) that you provide in your connection URL must be either
an absolute path, or
a relative path from the current working directory that is in effect when your application is running, which in your case appears to be "C:/Users/Gandalf/workspace/FubbleApp/bin/".
If you want your application to automatically search the CLASSPATH for the database file you will need to either provide your own code to do that or include some third-party code to do the search for you.
回答2:
I think that the accdb has to be outside of the jar file. and I'm saying this because jdbc is a protocol and you must be able to write in the db and writing in a db inside an archive you have to unarchive and archive the db again. I don't think you can do it easily... the solution is... relative to jar or absolute path. (in the same folder with the jar file)
来源:https://stackoverflow.com/questions/31947833/accessing-a-microsoft-access-database-that-is-saved-in-the-classpath