使用win32安全性模拟用户时发生pyodbc未知编码错误

2024-05-15 23:46:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用https://www.safaribooksonline.com/library/view/python-cookbook/0596001673/ch07s14.html中的示例连接到网络上另一个帐户可以访问的数据库。我得到的错误是:

r'DSN=测试'

LookupError:未知编码:utf-16le

import win32security, win32con

class Impersonate:
    def _ _init_ _(self, login, password):
        self.domain = 'bedrock'
        self.login = login
        self.password = password

    def logon(self):
        self.handle = win32security.LogonUser(self.login, self.domain,
            self.password, win32con.LOGON32_LOGON_INTERACTIVE,
            win32con.LOGON32_PROVIDER_DEFAULT)
        win32security.ImpersonateLoggedOnUser(self.handle)

    def logoff(self):
        win32security.RevertToSelf(  ) # terminates impersonation
        self.handle.Close(  ) # guarantees cleanup

if __name__=='__main__':
    a = Impersonate('barney', 'bambam')

    try:
        a.logon() # become the user
        try:
            # Do whatever you need to do, e.g.,:
            print win32api.GetUserName() # show you're someone else
            cnxn = pyodbc.connect(
                r'DSN=Test;'
            )
        finally:
            a.logoff() # Ensure return-to-normal no matter what
    except:
        print 'Exception:', sys.exc_type, sys.exc_value

Tags: selfyoudomaindefloginpassworddsnhandle
1条回答
网友
1楼 · 发布于 2024-05-15 23:46:28

多亏了帕特里克,文件帮助了我,我的解决方案是:

cnxn =  pyodbc.connect(
    r'DSN=HR;',encoding = 'utf-8',autocommit = True #To set the encoding for the connection
        ) 
cnxn.setencoding(encoding = 'utf-8') #To set the encoding for any queries

相关问题 更多 >