pypyodbc 连接显式字符串但不连接变量

pypyodbc connects with explicit string but not variable

我正在从用户处读取 SQL 服务器数据库的连接字符串,此处由 randomstring 表示。当我将 randomstring 打印到控制台时,它看起来很完美,而且我已经检查了十几次。但是,连接失败

pypyodbc.Error: ('IM002', '[IM002] [微软]

如果我明确地将完全相同的字符串传递给游标,则连接工作正常。我需要对字符串变量做任何特定的事情才能使用它吗?

    randomstring = ShowConnString(self.cframe).connstringtext
    print(randomstring)
    self.conn = pypyodbc.connect(randomstring)
    #self.conn = pypyodbc.connect(driver='{SQL Server}', server='(local)', database='Audit', uid='sa', pwd='password')

编辑:打印(随机字符串)输出:

pypyodbc.connect(driver='{SQL Server}', server='(local)', database='Audit', uid='sa', pwd= 'password')

首先要注意的是,您的第二个(注释掉的)示例没有与 "explicit [connection] string" 连接,它使用了一系列 关键字参数 ("kwargs") 以指定 driverserver 等。注意关键字参数形式之间的细微差别 ...

self.conn = pypyodbc.connect(driver='{SQL Server}', server='(local)', database='Audit', uid='sa', pwd='password')

...和连接字符串形式:

self.conn = pypyodbc.connect('driver={SQL Server};server=(local);database=Audit;uid=sa;pwd=password')

现在,如果您的 randomstring 变量确实包含

pypyodbc.connect(driver='{SQL Server}', server='(local)', database='Audit', uid='sa', pwd='password')

那么它肯定不是有效的 ODBC 连接字符串。即使它只是包含

driver='{SQL Server}', server='(local)', database='Audit', uid='sa', pwd='password'

这仍然不是有效的连接字符串,因为这些项目由逗号(而不是分号)分隔,并且值两边有引号。在将 randomstring 值的内容传递给 .connect 方法之前,您需要将其转换为正确的 ODBC 连接字符串。