【问题标题】:MS Access database locked by PythonMS Access 数据库被 Python 锁定
【发布时间】:2021-07-16 19:58:18
【问题描述】:

我正在使用 Python 将数据框写入 MS Access 数据库。它可以工作,但我似乎无法关闭连接(即数据库被 Python 锁定)。

这是我的代码:

# imports
import urllib
import pyodbc
import pandas as pd
from sqlalchemy import create_engine

# connection
connection_string = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
    r'DBQ=M:\Larry\Access\test2.accdb;'
    r'ExtendedAnsiSQL=1;'
)
connection_uri = f"access+pyodbc:///?odbc_connect={urllib.parse.quote_plus(connection_string)}"
engine = create_engine(connection_uri)

# create dataframe
d = {'name':['daryl','other daryl'],'team':['a','b']}
df = pd.DataFrame(d)

# write to database
df.to_sql('test',engine,if_exists='replace',index=False)

我尝试在创建引擎行之后添加这个:

conn = engine.connect()

数据帧写入数据库后:

conn.close()

我没有从这些添加中得到错误,但数据库仍然被锁定。如何关闭连接以解除锁定?

【问题讨论】:

  • 尝试配置引擎:engine_dispose()
  • M: 驱动器是否映射到网络共享?
  • @Parfait - 你的意思是 engine.dispose() 吗?那行得通,数据库不再被锁定。您想将其发布为答案,以便我将其标记为解决方案吗?
  • @GordThompson - 是的,M: 驱动器是网络共享。

标签: python pandas ms-access sqlalchemy-access


【解决方案1】:

由于你是用引擎对象维护一个数据库的连接实例,操作后考虑Engine.dispose()释放资源:

...
# write to database 
df.to_sql('test', engine, if_exists='replace', index=False)

engine.dispose()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多