我希望使用 pyodbc 通过 DSN 建立与 MS SQL 的连接。 我看到的是,除非我在连接字符串中指定用户名 (PID( 和密码 (PWD(,否则我无法连接到数据库,如下所示:
conn_str = 'DSN=MYMSSQL;UID=sa;PWD=password'
因此,如果我使用PID
并PWD
它有效,但是如果我将PID
和PWD
放在我的 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'