Accessing a Microsoft Access database that is save

2019-08-14 17:08发布

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:

enter image description here:

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

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-14 17:24

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)

查看更多
疯言疯语
3楼-- · 2019-08-14 17:36

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.

查看更多
登录 后发表回答