跳到主要内容

使用 Spring Boot 读取 Access DB 资料笔记

· 2 分钟阅读
Eric Cheng

为了要串接公司读卡机的打卡资料,读卡机存的资料是 MS 的 Access DB,测试了一下怎么用 JAVA 的 Spring Boot 读取 Access DB 资料,笔记如下

其实和用 Spring Boot 连接其他资料库 (MySQL, Postgresql, H2 ...etc) 几乎一样,相同的部份就不再仔细说明

Step 1: 取得 access db driver

以下笔记用的是 gradle,如果使用的是 maven 请自行转换

主要新增以下三个 dependencies

implementation 'net.sf.ucanaccess:ucanaccess:4.0.4' implementation 'com.healthmarketscience.jackcess:jackcess-encrypt:2.1.4' implementation 'org.bouncycastle:bcprov-ext-jdk15on:1.66'

Step 2: 设定连线

和连接其他资料库一样,需设定 url 和 driverClassName

原来 url 写 jdbc:ucanaccess://d:/PGA.mdb (d:/PGA.mdb 为档案路径,请自行更改),但会出现 exception

UCAExc:::4.0.4 Decoding not supported. Please choose a CodecProvider which supports reading the current database encoding.

google 找到这篇,照着做就 OK

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

简单说就是写一支程式 CryptCodecOpener

package com.taiwankk;

import java.io.File;
import java.io.IOException;
import net.ucanaccess.jdbc.JackcessOpenerInterface;
import com.healthmarketscience.jackcess.CryptCodecProvider;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;

public class CryptCodecOpener implements JackcessOpenerInterface {

@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 Jackcess documentation.
}

然后 url 增加 jackcessOpener=CryptCodecOpener (如果package 不同请自行更改)

完整设定如下:

# datasource
spring.datasource.url=jdbc:ucanaccess://d:/PGA.mdb;jackcessOpener=com.taiwankk.CryptCodecOpener
spring.datasource.driverClassName=net.ucanaccess.jdbc.UcanaccessDriver

Step 3 写 SQL 取得资料

example 的 SQL

select EmpID, Name, Date, Status, FORMAT(Date, 'yyyy/MM/dd') AS CD from Access
where FORMAT(Date, 'YYYY/MM/DD') = FORMAT(NOW, 'YYYY/MM/DD')
order by Date desc

就可以取得今天的资料了

2021-09-01_170648.png

版权声明


這是 google 廣告