我有一个连接数据库的脚本。我想从脚本中提取服务器,用户,密码,db并将其放入配置文件中。我成功地从配置文件中提取了值。我遇到的问题是当我在语法中有变量时pymssql.connect失败。我在下面粘贴了我的示例代码。这可能吗?
###database connection
config = configparser.ConfigParser()
config.read('test.config')
server = config['DEFAULT']['SQLServer']
db = config['DEFAULT']['Database']
user = config['DEFAULT']['User']
password = config['DEFAULT']['Password']
###this works
####conn = pymssql.connect(host='Server1', user='Joe',password='MyPass', database='MyDB')
###this doesn't
try:
conn = pymssql.connect(host=server, user=user,password=password, database=db)
except Exception as e:
print(str(e))
sys.exit()
答案 0 :(得分:0)
这是我检索连接属性和连接的sql server数据库的方法
**App.ini file**
[CoreContext]
host=sservername.database.windows.net
user=dbuser@servername
password=password
database=DeltaXCore
**Connection.py file**
appConfig = ConfigParser.ConfigParser()
appConfig.read("App.ini")
ConnectionString.HOST = appConfig.get("CoreContext", "host")
CoreConnectionString.USER = appConfig.get("CoreContext", "user")
CoreConnectionString.PASSWORD = appConfig.get("CoreContext", "password")
CoreConnectionString.DATABASE = appConfig.get("CoreContext", "database")
pymssql.connect(host=objdeltaxConnectionString.HOST, user=objdeltaxConnectionString.USER,password=objdeltaxConnectionString.PASSWORD, database=objdeltaxConnectionString.DATABASE)