永久更改 Microsoft Access 数据库的密码(通过 Python)

Permanently changing the password of an Microsoft Access DB (via Python)

我有一个受密码保护的 Microsoft Access 文件,我需要 运行 直接连接到该 Access 文件的 Tableau Prep 流程。 (例如,我需要每天运行)

Tableau Prep 文件不存储密码等连接信息。

我可以从命令行 运行 Tableau Prep 并给它一个带有凭据的 JSON 文件,但到目前为止,据我所知,它不支持 Access。

所以我的 idea/solution 到目前为止(在 python 脚本中):1-

  1. 从 Access 文件中删除密码(如何?)
  2. 运行 从命令行运行 Tableau Prep 的批处理文件
  3. 恢复密码

我的主要问题是不知道如何使用 Python 脚本删除 Access DB 的密码,因此我可以完全自动化 运行 设置 Tableau Prep 文件的过程。

您可以使用 pyodbc 和 ALTER DATABASE PASSWORD 命令(感谢 HansUp 指出这一点!)。

这仅适用于启用扩展 ANSI SQL 的独占连接。

您可以使用以下代码:

import pyodbc
constr = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Path\To\Db.accdb;Exclusive=1;Pwd=SuperSecurePassword;ExtendedAnsiSQL=1;' 
#Exclusive connection, with password and extended ANSI SQL
cnxn = pyodbc.connect(constr)
crsr = cnxn.cursor()
#Decrypt
crsr.execute('ALTER DATABASE PASSWORD NULL SuperSecurePassword')
cnxn.commit()
cnxn.close()

#Perform operations here

constr = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Path\To\Db.accdb;Exclusive=1;ExtendedAnsiSQL=1;' 
#Exclusive connection, extended ANSI SQL, no password
cnxn = pyodbc.connect(constr)
crsr = cnxn.cursor()
#Encrypt
crsr.execute('ALTER DATABASE PASSWORD SuperSecurePassword NULL')
cnxn.commit()
cnxn.close()

或者,您可以使用 COM encrypt/dencrypt 您的数据库。

import win32com.client as comclient
import os
DBEngine = comclient.Dispatch("DAO.DBEngine.120")
dbLangGeneral = ';LANGID=0x0409;CP=1252;COUNTRY=0'

#Create a copy without a password
DBEngine.CompactDatabase('Path_to_database', 'Path_to_copy', dbLangGeneral + ';PWD=', 0, ';PWD=MySuperSecretPass')

#Do stuff with copy

#Delete original
os.remove('Path_to_database')

#Create encrypted copy at location of original
DBEngine.CompactDatabase('Path_to_copy', 'Path_to_database', dbLangGeneral + ';PWD=MySuperSecretPass')
os.remove('Path_to_copy')

这会制作一个压缩的未加密数据库副本,然后执行操作,然后再次压缩它。

此代码假定您使用 dbLangGeneral 作为排序规则常量,您可以在需要时将其切换为不同的排序规则。