我正在寻找使用pyodbc通过DSN建立与MS SQL的连接。我看到的是,除非我像这样在连接字符串中指定用户名(PID)和密码(PWD),否则我无法连接到数据库:

conn_str = 'DSN=MYMSSQL;UID=sa;PWD=password'


因此,如果我使用PIDPWD可以工作,但是如果我将PIDPWD放在我的DSN配置(MYMSSQL)中并从conn_str删除这两个属性,则它不起作用,如下所示DSN配置:

[MYMSSQL]
Description         = Test to SQLServer
Driver              = FreeTDS
Servername          = MYMSSQL
UID                 = sa
PWD                 = password
Database            = tempdb


从pyodbc API文档中观察到,没有UID和PWD,没有办法做到这一点

def connect(p_str, autocommit=False, ansi=False, timeout=0, **kwargs): # real signature unknown; restored from __doc__
    """
    connect(str, autocommit=False, ansi=False, timeout=0, **kwargs) --> Connection

    Accepts an ODBC connection string and returns a new Connection object.

    **The connection string will be passed to SQLDriverConnect, so a DSN connection
    can be created using:**

      **cnxn = pyodbc.connect('DSN=DataSourceName;UID=user;PWD=password')**

    To connect without requiring a DSN, specify the driver and connection
    information:

      DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=user;PWD=password

    Note the use of braces when a value contains spaces.  Refer to SQLDriverConnect
    documentation or the documentation of your ODBC driver for details.

    The connection string can be passed as the string `str`, as a list of keywords,
    or a combination of the two.  Any keywords except autocommit, ansi, and timeout
    (see below) are simply added to the connection string.

      connect('server=localhost;user=me')
      connect(server='localhost', user='me')
      connect('server=localhost', user='me')

    The DB API recommends the keywords 'user', 'password', and 'host', but these
    are not valid ODBC keywords, so these will be converted to 'uid', 'pwd', and
    'server'.

    pass

最佳答案

我处理过的ODBC驱动程序管理器(Windows的内置DM和Linux上的unixODBC)静默地忽略了“系统DSN”和“用户DSN”定义中的UID=PWD=条目。它们确实尊重“文件DSN”定义中的那些条目,因此您可以在包含以下内容的安全位置中创建名为“ mymssql.dsn”的文件

[ODBC]
Description         = Test to SQLServer
Driver              = FreeTDS
Servername          = MYMSSQL
UID                 = sa
PWD                 = password
Database            = tempdb


然后使用

conn_str = 'FILEDSN=/path/to/mymssql.dsn'

关于python - pyodbc DSN-在连接字符串中不带UID和PWD的情况下连接到SQL Server,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52948218/

10-12 22:53