Python连接Microsoft SQL Server数据库详解

以下是使用 Python 连接 Microsoft SQL Server 数据库的详细步骤和代码示例:


一、准备工作

1. 安装必要的库

推荐使用 pyodbcpymssql 库:

# 使用 pyodbc(推荐)
pip install pyodbc

# 使用 pymssql
pip install pymssql
2. 安装 SQL Server ODBC 驱动
  • Windows:下载并安装 ODBC Driver for SQL Server
  • Linux
    # Ubuntu/Debian
    sudo apt-get install unixodbc unixodbc-dev
    sudo apt-get install freetds-dev freetds-bin
    
    # CentOS/RHEL
    sudo yum install unixODBC unixODBC-devel
    sudo yum install freetds freetds-devel
    

  • 二、连接数据库代码示例

    方法 1:使用 pyodbc
    import pyodbc
    
    # 连接字符串参数
    server = 'your_server_name'        # 例如:'localhost' 或 '192.168.1.100,1433'
    database = 'your_database_name'    # 数据库名称
    username = 'your_username'         # 登录账号
    password = 'your_password'         # 登录密码
    
    # 创建连接字符串(注意驱动名称可能因版本不同)
    conn_str = f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
    
    try:
        # 建立连接
        conn = pyodbc.connect(conn_str)
        cursor = conn.cursor()
    
        # 执行查询
        cursor.execute('SELECT TOP 5 * FROM YourTableName')
        
        # 获取结果
        rows = cursor.fetchall()
        for row in rows:
            print(row)
    
    except pyodbc.Error as e:
        print(f"数据库连接或查询失败: {e}")
    
    finally:
        # 关闭连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()
    
    方法 2:使用 pymssql
    import pymssql
    
    server = 'your_server_name'
    database = 'your_database_name'
    username = 'your_username'
    password = 'your_password'
    
    try:
        # 建立连接
        conn = pymssql.connect(server=server, user=username, password=password, database=database)
        cursor = conn.cursor()
    
        # 执行查询
        cursor.execute('SELECT TOP 5 * FROM YourTableName')
        
        # 获取结果
        rows = cursor.fetchall()
        for row in rows:
            print(row)
    
    except pymssql.Error as e:
        print(f"数据库连接或查询失败: {e}")
    
    finally:
        # 关闭连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()
    

    三、常见操作示例

    1. 插入数据
    try:
        cursor.execute("INSERT INTO YourTable (Column1, Column2) VALUES (?, ?)", ('Value1', 'Value2'))
        conn.commit()  # 提交事务
        print("插入成功")
    except Exception as e:
        conn.rollback()  # 回滚事务
        print(f"插入失败: {e}")
    
    2. 更新数据
    try:
        cursor.execute("UPDATE YourTable SET Column1 = ? WHERE Column2 = ?", ('NewValue', 'ConditionValue'))
        conn.commit()
        print("更新成功")
    except Exception as e:
        conn.rollback()
        print(f"更新失败: {e}")
    
    3. 调用存储过程
    cursor.execute("EXEC YourStoredProcedure @Param1=?, @Param2=?", ('Value1', 'Value2'))
    result = cursor.fetchall()
    

    四、常见问题解决

    1. 连接错误 [IM002] [Microsoft][ODBC Driver Manager] Data source name not found
  • 原因:ODBC 驱动名称不正确。
  • 解决
  • 检查已安装的 ODBC 驱动名称:
    print(pyodbc.drivers())  # 查看所有已安装的驱动
    
  • 修改连接字符串中的驱动名称(例如 DRIVER={SQL Server};)。
  • 2. 认证失败
  • 解决
  • 检查 SQL Server 是否启用 SQL Server 身份验证
  • 确认防火墙是否允许访问 SQL Server 端口(默认 1433)。
  • 3. Linux 环境下的编码问题
  • 解决:在连接字符串中添加 charset='utf8'
    conn = pymssql.connect(server, username, password, database, charset='utf8')
    

  • 五、连接字符串参数详解

    参数名 示例值 说明
    DRIVER ODBC Driver 17 for SQL Server ODBC 驱动名称
    SERVER localhost,1433 服务器地址和端口
    DATABASE AdventureWorks 数据库名称
    UID sa 用户名
    PWD your_password 密码
    Trusted_Connection yes 使用 Windows 身份验证

    六、推荐工具

  • SSMS (SQL Server Management Studio):用于管理和调试数据库。
  • DBeaver:跨平台的数据库管理工具。
  • 如果需要进一步优化或处理复杂场景(如连接池、异步操作),可以使用 SQLAlchemy 库。

    作者:局外人_Jia

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python连接Microsoft SQL Server数据库详解

    发表回复