You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pyodbc连接Python与SQL Server的配置文件编写问题求助

配置文件的作用
  • 代码与配置解耦:切换开发、测试、生产等不同环境的数据库时,只需要修改配置文件内容,不需要改动业务逻辑代码,降低出错概率
  • 敏感信息安全:后续如果需要使用账号密码方式连接数据库(而非可信连接),硬编码在代码里的凭证很容易随着代码提交泄露,放到配置文件中可以单独管控
  • 统一参数管理:所有数据库相关参数集中在一个文件,修改、排查问题时不需要遍历多个业务代码文件
具体实现步骤

我们用Python内置的configparser模块实现,不需要额外安装第三方依赖。

步骤1:创建配置文件

在项目根目录新建名为config.ini的配置文件,内容如下:

[database]
driver = SQL Server
server = .\TEST_SERVER
database = index_changes
trusted_connection = yes

后续需要修改连接参数时,直接修改这个文件即可。

步骤2:修改原有代码,加入配置读取逻辑

修改后的完整代码如下:

import pyodbc
import configparser
import os
import sqlalchemy as sa
import urllib
import pandas as pd

# 读取配置文件,用绝对路径避免不同运行环境下路径读取失败
conf = configparser.ConfigParser()
conf_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini')
conf.read(conf_path, encoding='utf-8')
db_conf = conf['database']

class SQL_Database:
    def __init__(self, driver, server, database, trusted_connection):
        self.driver = driver
        self.server = server
        self.database = database
        self.trusted_connection = trusted_connection

    def create_server_connection(self):
        connection = None
        try:
            connection = pyodbc.connect(
                f'Driver={self.driver};'
                f'Server={self.server};'
                f'Database={self.database};'
                f'Trusted_Connection={self.trusted_connection};'
            )
            print("SQL Server数据库连接成功")
        except pyodbc.Error as err:
            print(f"连接失败: {err}")
        return connection

# 直接从配置中读取参数初始化连接,不需要硬编码任何参数
conn = SQL_Database(
    driver=db_conf.get('driver'),
    server=db_conf.get('server'),
    database=db_conf.get('database'),
    trusted_connection=db_conf.get('trusted_connection')
).create_server_connection()

注:原有代码中连接成功的打印内容写的是MySQL,属于笔误,上述代码已经修正。

步骤3:安全配置(可选)

如果使用Git管理代码,一定要把config.ini加入到.gitignore文件中,避免配置文件被提交到代码仓库。可以额外提供一个config.example.ini的模板文件,去掉敏感信息,方便其他开发人员参考配置。

内容的提问来源于stack exchange,提问作者Zack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:18:02