如果您想要使用 CPython 的快速而肮脏的方式(也适用于 3.X python):
安装python后安装PYWIN32http://sourceforge.net/projects/pywin32/files/pywin32/
导入以下库:
导入odbc
我创建了以下获取 SQL Server odbc 驱动程序的方法(根据您的 Windows 版本,命名略有不同,因此无论如何都会得到它):
def getSQLServerDriver():
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ODBC\ODBCINST.INI")
sqlServerRegExp = re.compile('sql.*server', re.I | re.S)
try:
for i in range(0, 2048):
folder = winreg.EnumKey(key, i)
if sqlServerRegExp.match(folder):
return folder.strip()
except WindowsError:
pass
注意:如果您使用上述函数,您还需要导入这两个库:winreg 和 re
然后您使用此处定义的 odbc API 1 信息:http://www.python.org/dev/peps/pep-0248/
您的连接接口字符串应该如下所示(假设您使用我上面的方法来获取 ODBC 驱动程序名称,并且它是受信任的连接):
dbString = "Driver={SQLDriver};Server=[SQL Server];Database=[Database Name];Trusted_Connection=yes;".replace('{SQLDriver}', '{' + getSQLServerDriver() + '}')
这种方法有很多缺点。由于只支持 ODBC API 1,所以它很笨拙,而且我遇到的 API 或 ODBC 驱动程序中存在一些小错误,但它确实可以在 Windows 中的所有 CPython 版本中完成工作。