Debian11用Python3和JDBC操作ACCESS

主要步骤如下:

安装java环境

UCanAccess需要jar环境,这里我们直接装OpenJDK 11:

1
sudo apt install default-jdk

驱动下载

下载并解压UCanAccess JDBC驱动程序
UCanAccess JDBC驱动程序下载
下载解压后,可以用终端直接操作access数据库,运行UCanAccess-5.0.1.bin/console.sh,操作如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
bash console.sh
/path/to/UCanAccess-5.0.1.bin
Please, enter the full path to the access file (.mdb or .accdb): /path/to/stuTest.mdb
Please, enter password: ******
WARNING:Error in the metadata of the table login_log: table's row count in the metadata is 464 but 466 records have been found and loaded by UCanAccess. All will work fine, but it's better to repair your database.
......
Loaded Tables:
<你的数据表>, xxx, xxx
Loaded Queries:
查询次数
Loaded Procedures:
替换(), 插入列()
Loaded Indexes:
......
UCanAccess>
Copyright (c) 2021 Marco Amadei
UCanAccess version 5.0.1
You are connected!!
Type quit to exit

Commands end with ;

Use:
export [--help] [--bom] [-d <delimiter>] [-t <table>] [--big_query_schema <pathToSchemaFile>] [--newlines] <pathToCsv>;
for exporting the result set from the last executed query or a specific table into a .csv file

UCanAccess>select count(*) from <你的数据表>;

·-----·
| C1 |
·-----·
| 466 |
·-----·

模块安装

1
pip install JPype1 jaydebeapi

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import jaydebeapi

# 文件路径要用绝对路径
db_path = "/path/to/access数据库.mdb"
psw = "access数据库的密码"

# 以下文件`UCanAccess-5.0.1.bin`是`UCanAccess JDBC`驱动程序下载解压后的文件路径
ucanaccess_jars = [
"/psth/to/UCanAccess-5.0.1.bin/ucanaccess-5.0.1.jar",
"/psth/to/UCanAccess-5.0.1.bin/lib/commons-lang3-3.8.1.jar",
"/psth/to/UCanAccess-5.0.1.bin/lib/commons-logging-1.2.jar",
"/psth/to/UCanAccess-5.0.1.bin/lib/hsqldb-2.5.0.jar",
"/psth/to/UCanAccess-5.0.1.bin/lib/jackcess-3.0.1.jar",
]
classpath = ":".join(ucanaccess_jars)
conn = jaydebeapi.connect(
"net.ucanaccess.jdbc.UcanaccessDriver",
f"jdbc:ucanaccess://{db_path};password={psw}",
["", ""],
classpath
)
## 查询
cur = conn.cursor()
cur.execute("select * from <你的数据表>")
result = cur.fetchall()
print("所有数据:", result)
print("第二条数据:", result[1])
# 输出:
所有数据是: [(1, '赵大', 20), (2, '钱二', 30), (3, 'sunsan', 25)]
第二条数据是: (2, '钱二', 30)

如图:
debian11_jdbc_access.png

1
2
3
## 插入
cur.execute("insert into tb_usr (ID,usr_name,usr_age) values (4,'李四',32),(5,'周五',38)")
conn.commit

如图:
debian11_jdbc_access-1.png

参考资料:
1、LINUX通过python连接ACCESS(.mdb和.accdb文件)数据库
2、如何在 Debian 10 Linux 上安装 Java