使用 win32com 在 Python 中使用 SMO DLL
我正在尝试通过 pyWin32 使用 Python 2.7 中的 SQL Server SMO 库。我可以导入 win32com
,但我在访问该库的任何尝试中都受到了阻碍。我正在尝试的代码如下。
import sys
sys.path.append(r'C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies')
import win32com.client
server = win32com.client.Dispatch('Microsoft.SqlServer.Management.SMO.Server')
def main():
print server
if __name__ == '__main__':
main()
运行此代码时,我收到 pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
。
看来我只是在调用 Dispatch
时弄错了库的名称,但我无法找出任何方法来知道它应该是什么。
看起来这实际上可能是路径问题。
这有效:
import win32api
win32api.LoadLibrary(r'C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll')
但是,这不起作用:
import sys
sys.path.append(r'C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies')
import win32api
win32api.LoadLibrary(r'Microsoft.SqlServer.Smo.dll')
I'm attempting to use the SQL Server SMO library from Python 2.7 using pyWin32. I can import win32com
, but I've been stymied in any attempt to access the library. The code I am attempting is below.
import sys
sys.path.append(r'C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies')
import win32com.client
server = win32com.client.Dispatch('Microsoft.SqlServer.Management.SMO.Server')
def main():
print server
if __name__ == '__main__':
main()
When this code is run, I get pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
.
It seems likely that I am simply getting the library's name wrong in the call to Dispatch
, but I can't figure out any way to know what it should be.
It seems like this may actually be a path problem.
This works:
import win32api
win32api.LoadLibrary(r'C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll')
However, this does not:
import sys
sys.path.append(r'C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies')
import win32api
win32api.LoadLibrary(r'Microsoft.SqlServer.Smo.dll')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
win32com 用于使用 COM 库,它不了解有关 .NET 程序集的任何信息。目前,无法直接从 CPython 使用 .NET,因此您的选择是使用 IronPython 或用 C# 或其他语言编写命令行工具,然后从 Python 调用它。
win32com is for using COM libraries and it doesn't know anything about .NET assemblies. Currently, there is no way to use .NET directly from CPython, so your options are to use IronPython or write a command line tool in C# or whatever and then call it from Python.
除了 @Pondlife 的答案(对于所提出的问题是正确的)之外,还可以使用 Python 在 CPython 中加载 .NET 程序集对于 .NET 模块和以下代码:
为了使其工作,我需要手动将程序集的路径添加到
PYTHONPATH
。我无法使用 sys.path.append 让它工作。In addition to @Pondlife's answer, which is correct for the question asked, it is possible to load .NET assemblies in CPython using the Python for .NET module and the following code:
To make this work, I needed to add the assembly's path to
PYTHONPATH
manually. I couldn't get it to work usingsys.path.append
.