為了要串接公司讀卡機的打卡資料,讀卡機存的資料是 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
就可以取得今天的資料了