python - 通过 dsn 错误的 ODBC 连接

标签 python sql odbc pyodbc

我在尝试通过 pyodbc.connect 调用我的 uid 和密码时遇到问题

这是我的 odbc.ini:

[my_dsn]
Driver= SQL Server
Server=my_server
User=uid_reader
Password=password_reader
MultiSubnetFailover=Yes
Database=master

当我硬编码时,它工作得很好,我可以连接

test_uid = 'uid_reader'
test_password = 'password_reader'

conn = pyodbc.connect(r'DSN=my_dsn;UID={a};PWD={b}'.format(a=test_uid,b=test_password))

当我从 odbc.ini 调用 dsn 变量时,它不起作用

conn = pyodbc.connect(r'DSN=my_dsn;UID=User;PWD=Password')

Error: ('28000', "[28000] [unixODBC][Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Login failed for user 'User'. (18456) (SQLDriverConnect)")

我想在我的 odbc.ini 中隐藏密码,这样当我调用 pyodbc.connect 时它就不会出现

最佳答案

conn = pyodbc.connect(r'DSN=my_dsn;UID=User;PWD=Password') 似乎使用了 my_dsn 的文字字符串值、用户密码。您可以尝试使用关键字 like the documentation here ,或执行与您对硬编码解决方案所做的类似的字符串格式设置,但将其替换为加载的配置数据。

来自 the documentation看来您应该能够直接从 ini 加载 DSN 信息,但我自己也没有取得太大成功。需要注意的是,文档只说您可以可能使用登录凭据,所以这可能取决于驱动程序?

无论哪种方式,下面是一个使用 configparser 的版本应该可以工作。对某些人来说,这可能被认为是黑客行为。

import pyodbc
from configparser import ConfigParser

config = ConfigParser()
config.read(configfile)   # your odbc.ini file path and name
dsn = config['my_dsn']

#If you want to use Keywords:

conn = connect(driver=dsn['driver'], server=dsn['server'], database=dsn['database'], uid=dsn['user'], pwd=dsn['password'])

#If you want to use string formatting with list comprehension instead:
conn = pyodbc.connect(''.join(['{0}={1}; '.format(k, l) for k, l in d.items()])

关于python - 通过 dsn 错误的 ODBC 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349998/

相关文章:

python - 比较特定列的 70% 的行

python - 将 .c 文件从 Cython 转换为独立的 .exe 和编译 gcc 错误

python - Django:管理界面中的 OneToOne 下拉菜单和独特的关联

表中所选记录的一列上的 MySQL 时间差

java - JAR 文件无法识别 mysql 数据库

python - 这个python函数如何获取它的参数?

sql - 基于以前的值更新 SQL SERVER 2005

SQL 查询 - Count() 和内部连接

c# - 如何更改 DataContext 中的数据库名称

c++ - 对于 SQLCHAR 类型参数,ODBC SQLBindParameter 的 ColumnSize 参数可以是 strlen(param) + 1 吗?