2012-04-10 49 views
2

我有一個的.ini(配置文件),其中我提到的服務器名稱,數據庫名稱,用戶名和密碼,我可以我的應用程序連接到MSSQL上述連接語句提到如何將配置變量值傳入pyodbc connect命令?

self.db = pyodbc.connect('driver={SQL Server};server=homeserver;database=testdb;uid=home;pwd=1234')

相應的數據現已在config.ini中 ' self.configwrite = ConfigParser.RawConfigParser() configread = SafeConfigParser() configread.read( '的config.ini')

driver = configread.get('DataBase Settings','Driver') 
server = str(configread.get('DataBase Settings','Server')) 
db = str(configread.get('DataBase Settings','Database')) 
user = str(configread.get('DataBase Settings','Username')) 
password = str(configread.get('DataBase Settings','Password'))' 

我將如何通過pyodbc連接語句中的這些變量

我累了這個 self.db = pyodbc.connect('driver={Driver};server=server;database=db;uid=user;pwd=password') 出現錯誤。

回答

4
self.db = pyodbc.connect('driver={%s};server=%s;database=%s;uid=%s;pwd=%s' % (driver, server, db, user, password)) 

%S用於根據%後其爲包括變量到字符串

變量被放置到串

6

connect函數其他選擇:

# using keywords for SQL Server authentication 
self.db = pyodbc.connect(driver=driver, server=server, database=db, 
         user=user, password=password) 

# using keywords for Windows authentication 
self.db = pyodbc.connect(driver=driver, server=server, database=db, 
         trusted_connection='yes')