Java 如何将 UCanAccess 连接到使用数据库密码加密的 Access 数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31429939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:07:19  来源:igfitidea点击:

How to connect UCanAccess to an Access database encrypted with a database password?

javams-accessjdbcms-access-2010ucanaccess

提问by

I've developed a Java application (a dictionary) with an Access database to store the words of the dictionary and I'm getting ready to distribute it. I want to encrypt my database with a password to prevent people to access my words. When I set a passwords the Java code shows this Exception

我开发了一个带有 Access 数据库的 Java 应用程序(字典)来存储字典中的单词,我正准备分发它。我想用密码加密我的数据库,以防止人们访问我的话。当我设置密码时,Java 代码显示此异常

net.ucanaccess.jdbc.UcanaccessSQLException: Decoding not supported.  Please choose a CodecProvider which supports reading the current database encoding.
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:247)

Here is my connection code before encryption of my database with password ....

这是我使用密码加密数据库之前的连接代码....

String s1="jdbc:ucanaccess://";
String user="";
String pass="";
String s4="words.accdb";

public void connectToDB(){
        //database connection
        try {
            conn = DriverManager.getConnection(s1+s4,user,pass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //end of database connection
    }

Here is the code after the encryption with password for example 12345...

这是使用密码加密后的代码,例如 12345 ...

String s1="jdbc:ucanaccess://";
String user="";
String pass="12345";
String s4="words.accdb";

public void connectToDB(){
        //database connection
        try {
            conn = DriverManager.getConnection(s1+s4,user,pass);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //end of database connection
    }

采纳答案by Hamreen Ahmad

Steps of How to connect UCanAccess to an Access database encrypted with a database password

如何将 UCanAccess 连接到使用数据库密码加密的 Access 数据库的步骤

Step 1:
Add these two packages to your project (Hymancess-encrypt.jar, bcprov-ext-jdk15on-152)

第一步:
将这两个包添加到你的项目中(Hymancess-encrypt.jar、bcprov-ext-jdk15on-152)

You can download the two packages from the following links:

您可以从以下链接下载这两个软件包:

Hymancess Encrypt
Bouncy Castle

Hymancess加密充气
城堡

Step 2:
You have to add this class to your project folder

第 2 步:
您必须将此类添加到您的项目文件夹中

import java.io.File;
import java.io.IOException;
import net.ucanaccess.jdbc.HymancessOpenerInterface;
import com.healthmarketscience.Hymancess.CryptCodecProvider;
import com.healthmarketscience.Hymancess.Database;
import com.healthmarketscience.Hymancess.DatabaseBuilder;

public class CryptCodecOpener implements HymancessOpenerInterface {
         @Override
    public Database open(File fl,String pwd) throws IOException {
       DatabaseBuilder dbd =new DatabaseBuilder(fl);
       dbd.setAutoSync(false);
       dbd.setCodecProvider(new CryptCodecProvider(pwd));
       dbd.setReadOnly(false);
       return dbd.open();
    }
  //Notice that the parameter setting autosync =true is recommended with UCanAccess for performance reasons. 
  //UCanAccess flushes the updates to disk at transaction end. 
  //For more details about autosync parameter (and related tradeoff), see the Hymancess documentation. 
}

like this

像这样

enter image description here

在此处输入图片说明

step 3:
use the following connection code

第三步:
使用下面的连接代码

public void connectToDB(){
            try {
                conn = DriverManager.getConnection("jdbc:ucanaccess://words.accdb;HymancessOpener=CryptCodecOpener", "user", "pass");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
    }


You can also watch this video...https://www.youtube.com/watch?v=TT6MgBBkRSE


您也可以观看此视频... https://www.youtube.com/watch?v=TT6MgBBkRSE

回答by rmbl

Your Link to the jdbc driver (s1) seems to be invalid.

您指向 jdbc 驱动程序 (s1) 的链接似乎无效。

Look at the pattern i found while googleing it from this Site

看看我在这个网站上用谷歌搜索时发现的模式

 String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\IJTS EXAMPLES\Database11.accdb;PWD=1234";

Here is a sample from a Site

这是来自站点的示例

private void initializeConnection()
{

Connection con ;
try
{

// Load Class Definition for Database Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// set this to a MS Access DB you have on your machine
String curDir = System.getProperty("user.dir");
String filename = curDir +"/test.mdb";

String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\test.mdb;READONLY=true";

// Get connection from the DriverManager
con = DriverManager.getConnection( database,"Admin","test" );


} catch (Exception e) {

System.out.println("Database Connection Problem");

}

}

Please not that you have to change the string by replacing parts with your credentials

请注意,您必须通过用您的凭据替换部分来更改字符串

回答by Constantin

I assume you have set the database password from within MSAccess, encrypting it.

我假设您已经在 MSAccess 中设置了数据库密码,并对其进行了加密。

To connect to this type of database, you need the correct connection string and connect via odbc.

要连接到这种类型的数据库,您需要正确的连接字符串并通过 odbc 连接。

Here is a link to get the connection strings for MSAccess https://www.connectionstrings.com/access/

这是获取 MSAccess 连接字符串的链接 https://www.connectionstrings.com/access/

A good post on the subject can be found here How can I add a password to this JDBC:ODBC connection string that is trying to connect to an MS Access database

可以在此处找到有关该主题的好帖子 How can I add a password to this JDBC:ODBC connection string that is试图连接到 MS Access 数据库

I would suggest you use a different type of embedded database to do all of this for java. Use h2, which is far better pure java solution

我建议您使用不同类型的嵌入式数据库为 Java 执行所有这些操作。使用h2,这是更好的纯java解决方案

http://www.h2database.com/html/main.html

http://www.h2database.com/html/main.html

code example

代码示例

public class HelloWorld {

    /**
     * Called when ran from command line.
     *
     * @param args ignored
     */
    public static void main(String... args) throws Exception {
        // delete the database named 'test' in the user home directory
        DeleteDbFiles.execute("~", "test", true);

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
        Statement stat = conn.createStatement();    
        stat.execute("create table test(id int primary key, name varchar(255))");
        stat.execute("insert into test values(1, 'Hello')");
        ResultSet rs;
        rs = stat.executeQuery("select * from test");
        while (rs.next()) {
            System.out.println(rs.getString("name"));
        }
        stat.close();
        conn.close();
    }    
}

Where are the Database Files Stored?

数据库文件存储在哪里?

When using database URLs like jdbc:h2:~/test, the database is stored in the user directory. For Windows, this is usually C:\Documents and Settings\ or C:\Users\.

使用 jdbc:h2:~/test 等数据库 URL 时,数据库存储在用户目录中。对于 Windows,这通常是 C:\Documents and Settings\ 或 C:\Users\。

If the base directory is not set (as in jdbc:h2:test), the database files are stored in the directory where the application is started (the current working directory).

如果未设置基本目录(如 jdbc:h2:test),则数据库文件存储在应用程序启动的目录(当前工作目录)中。

When using the H2 Console application from the start menu, this is /bin. The base directory can be set in the database URL. A fixed or relative path can be used.

从开始菜单使用 H2 控制台应用程序时,这是 /bin。可以在数据库 URL 中设置基本目录。可以使用固定或相对路径。

When using the URL jdbc:h2:file:data/sample, the database is stored in the directory data (relative to the current working directory). The directory is created automatically if it does not yet exist.

当使用 URL jdbc:h2:file:data/sample 时,数据库存储在目录 data 中(相对于当前工作目录)。如果目录尚不存在,则会自动创建该目录。

It is also possible to use the fully qualified directory name (and for Windows, drive name). Example: jdbc:h2:file:C:/data/test

也可以使用完全限定的目录名称(对于 Windows,驱动器名称)。示例:jdbc:h2:file:C:/data/test

Passing the User Name and/or Password in the URL

在 URL 中传递用户名和/或密码

Instead of passing the user name as a separate parameter as in Connection conn = DriverManager. getConnection("jdbc:h2:~/test", "sa", "123");

而不是将用户名作为单独的参数传递给 Connection conn = DriverManager. getConnection("jdbc:h2:~/test", "sa", "123");

The user name (and/or password) can be supplied in the URL itself: Connection conn = DriverManager. getConnection("jdbc:h2:~/test;USER=sa;PASSWORD=123");

用户名(和/或密码)可以在 URL 本身中提供: Connection conn = DriverManager. getConnection("jdbc:h2:~/test;USER=sa;PASSWORD=123");

回答by jamadei

UCanaccess supports encryption through the dependencies injection pattern.

UCanaccess 支持通过依赖注入模式进行加密。

-You have to add Hymancess-encrypt and all related dependencies to your project

- 您必须将 Hymancess-encrypt 和所有相关的依赖项添加到您的项目中

-You have to code a class implementing the net.ucanaccess.jdbc.HymancessOpenerInterfaceas suggested in the ucanaccess web site

- 你必须编写一个类来实现net.ucanaccess.jdbc.HymancessOpenerInterfaceucanaccess 网站中的建议

-You have to pass the name of the above class in the jdbc url: if you named the implementation class com.pippo.Bingothen you have to build the jdbc url in this way:

- 你必须在jdbc url中传递上述类的名称:如果你命名了实现类com.pippo.Bingo那么你必须以这种方式构建jdbc url:

DriverManager.getConnection("jdbc:ucanaccess://c:/db/your_db_name.mdb;HymancessOpener=com.pippo.Bingo", "sa", pwd);