ADODBAPI No. Of Open Connection with database

懵懂的女人 提交于 2019-12-02 07:16:46

Personally I would be inclined to avoid fussing with adodbapi in this case and just have my Python script write a little VBScript to create a tab-separated list of machines with open connections, run the VBScript via subprocess.Popen, and parse the results:

import os
import subprocess

## test data
databaseFileSpec = r"Z:\pyTest.mdb"

vbsFileSpec =  os.environ['TEMP'] + r"\mypytemp.vbs"

scriptCode = """Option Explicit
Dim con, rst, strOut, strSeparator
Const adSchemaProviderSpecific = -1
Set con = CreateObject("ADODB.Connection")
con.Open( _
        "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source="""
scriptCode += databaseFileSpec
scriptCode += """")
Set rst = con.OpenSchema( _
        adSchemaProviderSpecific, _
        , _
        "{947bb102-5d43-11d1-bdbf-00c04fb92675}")
strOut = ""
strSeparator = ""
Do While Not rst.EOF
    If rst(2).Value = "True" Then
        strOut = strOut & strSeparator & Left(rst(0).Value, Len(Trim(rst(0).Value)) - 1)
        strSeparator = vbTab
    End If
    rst.MoveNext
Loop
WScript.Echo strOut
rst.Close
con.Close"""

f = open(vbsFileSpec, 'w')
f.write(scriptCode)
f.close()

tabString = subprocess.Popen(
    "cscript /nologo \"" + vbsFileSpec + "\"",
    shell=True,
    stdout=subprocess.PIPE).stdout.read()
os.remove(vbsFileSpec)

print 'The following machines are connected to "' + databaseFileSpec + '":'
for x in tabString.split("\t"):
    print x

When I have the database open on two different machines and run the above script I get

The following machines are connected to "Z:\pyTest.mdb":
TESTPC
GORD01
GORD01

My notebook (GORD01) shows up twice because I have the database open in Access and the VBScript also has a connection open while it is running.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!